I created a simple web application with Thymeleaf using Spring Boot. I use the application.properties file as configuration. What I'd like to do is add new properties such as name and version to that file and access the values from Thymeleaf.
I have been able to achieve this by creating a new JavaConfiguration class and exposing a Spring Bean:
@Configuration
public class ApplicationConfiguration {
@Value("${name}")
private String name;
@Bean
public String name() {
return name;
}
}
I can then display it in a template using Thymeleaf like so:
<span th:text="${@name}"></span>
This seems overly verbose and complicated to me. What would be a more elegant way of achieving this?
If possible, I'd like to avoid using xml configuration.
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.
SpEL expressions may also be used to define beans using annotation-based configuration metadata. To define a default value, use the @Value annotation on fields, methods, and method/constructor arguments.
We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name. For example, if we define a “staging” environment, that means we'll have to define a staging profile and then application-staging. properties.
You can get it via the Environment
. E.g.:
${@environment.getProperty('name')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With