How to access spring boot properties from freemarker template
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;
}
}
One option in spring boot 2:
@Configuration
public class CustomFreeMarkerConfig implements BeanPostProcessor {
@Value("${myProp}")
private String myProp;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof FreeMarkerConfigurer) {
FreeMarkerConfigurer configurer = (FreeMarkerConfigurer) bean;
Map<String, Object> sharedVariables = new HashMap<>();
sharedVariables.put("myProp", myProp);
configurer.setFreemarkerVariables(sharedVariables);
}
return bean;
}
}
Spring Boot 2.x changed class structure so it's no longer possible to subclass and keep the auto configuration like was possible with Spring Boot 1.x.