在构造函数中使用带有@Value的@ConfigurationProperties的Spring前缀

时间:2015-06-11 08:44:32

标签: spring spring-boot

我正在使用@SpringBootApplication批注使用Spring Boot(1.2.0.RELEASE)运行我的应用程序。

我尝试实现的是在每个@Value注释中使用以下内容而不使用长前缀:

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;
    }
}

我知道这可以在不使用@Value且需要setter(@ConfigurationProperties prefix not working)或http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties的情况下完成,但我尝试在构造函数中实现它。

2 个答案:

答案 0 :(得分:2)

我不确定@value的使用方法,但以下内容适用于我

@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

答案 1 :(得分:0)

试试这个

@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();
}

@ConfigurationProperties("prefix")
@Component
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;
    }

}
}