Tuno
Tuno

Reputation: 1330

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.

Upvotes: 7

Views: 12356

Answers (2)

jst
jst

Reputation: 1747

Try this:

@Service
public class DefaultService {

    private final String key1;
    private final String key2;

    @Autowired
    public DefaultService(ConfigSettings config) {
        this.key1 = config.getKey1();
        this.key2 = config.getKey2();
    }

    @Component
    @ConfigurationProperties("prefix")
    static class ConfigSettings {
        private String key1;
        private String key2;

        public String getKey1() {
            return key1;
        }
        public String getKey2() {
            return key2;
        }
        public void setKey1(String key1) {
            this.key1 = key1;
        }
        public void setKey2(String key2) {
            this.key2 = key2;
        }
    }

}

Upvotes: 0

Haim Raman
Haim Raman

Reputation: 12023

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

Upvotes: 5

Related Questions