Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 715
Pierre Gayvallet Avatar asked Jan 25 '16 09:01

Pierre Gayvallet


People also ask

How do I use FreeMarker template in spring boot?

Freemarker Template Files Spring boot looks for the The template files under classpath:/templates/. And for the file extension, you should name the files with . ftlh suffix since Spring Boot 2.2. If you plan on changing the location or the file extension, you should use the following configurations.

How do I view properties in spring?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

Which is the spring boot starter that has to be added to include FreeMarker template engine?

The spring-boot-starter-freemarker is starter for building Spring MVC applications with FreeMarker. The spring-boot-starter-jdbc is a starter for using JDBC in Spring Boot. This is City bean class. It contains item id, name, and population.

What is the use of FreeMarker template?

FreeMarker is a template engine, written in Java, and maintained by the Apache Foundation. We can use the FreeMarker Template Language, also known as FTL, to generate many text-based formats like web pages, email, or XML files.


1 Answers

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;
    }
}
like image 89
Pierre Gayvallet Avatar answered Oct 19 '22 12:10

Pierre Gayvallet