I am running my application with Spring Boot (1.2.0.RELEASE) using the @SpringBootApplication annotation.
What I try to achieve is to have the following without using long prefixes in each @Value annotation:
application.properties
prefix.key1=value1
prefix.key2=value2
DefaultService.java
@Service
@ConfigurationProperties("prefix")
public class DefaultService implements Service {
private final String key1;
private final String key2;
@Autowired
public DefaultService(@Value("${key1}") final String key1, @Value("${key2}") final String key2) {
this.key1 = key1;
this.key2 = key2;
}
}
I know that this can be done without using @Value and in need of setters (@ConfigurationProperties prefix not working) or with http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties but I try to achieve it in the constructor.
In Spring we can use the @Value annotation to set property or arguments values based on a SpEL expression. If we want to use the @Value annotation for a constructor argument we must not forget to add the @Autowired annotation on the constructor as well.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
@ConfigurationProperties works best with hierarchical properties that all have the same prefix; therefore, we add a prefix of mail. The Spring framework uses standard Java bean setters, so we must declare setters for each of the properties.
@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.
I am not sure about the usage of @value, but the following works for me
@Service
@ConfigurationProperties(prefix="prefix")
public class DefaultService {
private String key1;
private String key2;
@PostConstruct
public void report(){
System.out.println(String.format("key1=%s,key2=%s", key1,key2));
}
public void setKey1(String key1) {
this.key1 = key1;
}
public void setKey2(String key2) {
this.key2 = key2;
}
application.properties
prefix.key1=value1
prefix.key2=value2
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