Search code examples
javaspringspring-bootfreemarker

How to access spring boot properties from freemarker template


My problematic is really simple :

In my spring-boot web application, I have some env-related properties that the front/client-side needs to know about (let's say, a CORS remote url to call that is env dependant).

I have correctly defined my application-{ENV}.properties files and all the per-env-props mecanism is working fine.

The question I can't seem to find answer to is : how do you allow your freemarker context to know about your properties file to be able to inject them (specifically in a spring-boot app). This is probably very easy but I cant find any example...

Thanks,


Solution

  • Gonna answer myself :

    Easiest way in spring-boot 1.3 is to overrides the FreeMarkerConfiguration class :

    /**
     * Overrides the default spring-boot configuration to allow adding shared variables to the freemarker context
     */
    @Configuration
    public class FreemarkerConfiguration extends FreeMarkerAutoConfiguration.FreeMarkerWebConfiguration {
    
        @Value("${myProp}")
        private String myProp;
    
        @Override
        public FreeMarkerConfigurer freeMarkerConfigurer() {
            FreeMarkerConfigurer configurer = super.freeMarkerConfigurer();
    
            Map<String, Object> sharedVariables = new HashMap<>();
            sharedVariables.put("myProp", myProp);
            configurer.setFreemarkerVariables(sharedVariables);
    
            return configurer;
        }
    }