Access Property File in Spring Expression Language

I created a simple web application with Thymeleaf using Spring Boot. I use the application.properties file as a configuration. I would like to add new properties, such as name and version, to this file and access the values ​​from Thymeleaf.

I was able to achieve this by creating a new JavaConfiguration class and exposing the Spring Bean:

@Configuration public class ApplicationConfiguration { @Value("${name}") private String name; @Bean public String name() { return name; } } 

Then I can display it in the template using Thymeleaf:

 <span th:text="${@name}"></span> 

It seems too verbose and complicated for me. What would be a more elegant way to achieve this?

If possible, I would like to avoid using the xml configuration.

+5
source share
2 answers

You can get it through Environment . For instance:.

 ${@environment.getProperty('name')} 
+18
source

This is very easy to do in JavaConfig. Here is an example:

 @Configuration @PropertySource("classpath:my.properties") public class JavaConfigClass{ @Value("${propertyName}") String name; @Bean //This is required to be able to access the property file parameters public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } } 

Alternatively, this is the equivalent of XML:

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>my.properties</value> </property> </bean> 

Finally, you can use the environment variable, but there is a lot of additional code for this.

+1
source

Source: https://habr.com/ru/post/1205702/


All Articles