Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring prefix using @ConfigurationProperties with @Value in the constructor

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.

like image 352
Tuno Avatar asked Jun 11 '15 08:06

Tuno


People also ask

Can we use @value in 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.

What is the use of @value annotation in Spring?

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.

What is prefix in @ConfigurationProperties?

@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.

What does @value mean in Spring?

@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.


1 Answers

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
like image 144
Haim Raman Avatar answered Sep 22 '22 16:09

Haim Raman