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

我使用@
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的情况下完成,但我尝试在构造函数中实现它.

最佳答案 我不确定@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
点赞