Reputation: 2953
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,
Upvotes: 6
Views: 6874
Reputation: 1156
import freemarker.template.Configuration;
@Component
public class FreemarkerConfiguration {
@Autowired
private Configuration freemarkerConfig;
@Value("${myProp}")
private String myProp;
Map<String, Object> model = new HashMap();
model.put("myProperty", myProp);
// set loading location to src/main/resources
freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/");
Template template = freemarkerConfig.getTemplate("template.ftl");
String templateText = FreeMarkerTemplateUtils.
processTemplateIntoString(template, model);
}
step 2,
get property in freemarker template code.
<div>${myProperty}</td>
Upvotes: 0
Reputation: 17867
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.
Upvotes: 3
Reputation: 2953
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;
}
}
Upvotes: 4