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

Tun*_*uno 7 spring spring-boot

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

我试图实现的是在每个 @Value 注释中不使用长前缀的情况下实现以下目标:

应用程序属性

prefix.key1=value1
prefix.key2=value2
Run Code Online (Sandbox Code Playgroud)

默认服务.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Hai*_*man 4

我不确定 @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;
    }
Run Code Online (Sandbox Code Playgroud)

应用程序属性

prefix.key1=value1
prefix.key2=value2
Run Code Online (Sandbox Code Playgroud)