【问题标题】:Spring prefix using @ConfigurationProperties with @Value in the constructor在构造函数中使用 @ConfigurationProperties 和 @Value 的 Spring 前缀
【发布时间】:2015-08-26 20:31:50
【问题描述】:

我正在使用 @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 并且需要设置器 (@ConfigurationProperties prefix not working) 或使用 http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties 的情况下完成,但我尝试在构造函数中实现它。

【问题讨论】:

  • 我猜长前缀是您方案中的唯一选择。
  • 这将是一个不错的 Spring 功能请求。

标签: spring spring-boot


【解决方案1】:

我不确定@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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2013-05-26
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多