dev-resources.site
for different kinds of informations.
Inject Properties using @Value Annotations vs Environment vs @ConfigurationProperties
Inject Properties using @Value Annotations vs Environment vs @ConfigurationProperties
@Value Annotations vs Environment vs @ConfigurationProperties.
Spring provides some ways to inject properties from properties file. We have learned how to use them in 3 articles:
This tutorial helps you have a comparison view covering those solutions.
1. @Value Annotation
We can get property value anywhere by using @Value, we can inject default value, List/Arrays, special types (DateTime, Pattern), value that should be treated as null easily with just one line added. So it is very easy to implement.
@DateTimeFormat(pattern="yy/MM/dd HH:mm")
@Value("${config.time.key}")
private LocalDateTime time;
But to be sure that this is possible, PropertySourcesPlaceholderConfigurer must exist in the application contexts that placeholders resolution is required.
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { // return new PropertySourcesPlaceholderConfigurer(); PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); // configurer.setLocation(new ClassPathResource("myapp.properties")); configurer.setIgnoreUnresolvablePlaceholders(true); configurer.setNullValue("This is NULL"); return configurer; }
This approach also has another disadvantage that it makes each class which uses @Value depends on one or more property name. If we wanna change any property, we have to update all files which referenced it, or if we wanna find where it is used, we must make a text searching.
2. Environment
To work with Environment, we use @Autowired:
More at:
Inject Properties using @Value Annotations vs Environment vs @ConfigurationProperties
Featured ones: