【问题标题】:Why is @ConfigurationProperties not overriding defaults in my case?为什么@ConfigurationProperties 在我的情况下没有覆盖默认值?
【发布时间】:2015-03-23 21:12:05
【问题描述】:

我希望 spring boot 从我的 application.properties 中的条目中读取我的配置,但它们没有被激活。我的 application.properties 包含这些条目:

foo.user=nobody
foo.pass=notshared

我可以看到这个文件正在被读取(我只有两次文件:一次在 src-tree 中,一次在 bin 中自动复制。文件是相等的):

2015-03-23 21:55:18.199 DEBUG 25004 --- [main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'classpath:/application.properties' 

我有一个名为 FooConfig 的类:

@Component
@ConfigurationProperties(prefix = "foo")
public class FooConfig {
  private String user = "default";
  private String pass = "default";
...
}

我对这两个值都有 getter 和 setter。 我将此配置类自动连接到我的代码中:

@Component
public class FooFunctions {
    @Autowired
    public FooFunctions(FooConfig fooConfig) {
        log.debug("user={}", fooConfig.getUser());
...

问题是打印的是默认值“default”,而不是 application.properties 中的值。 有什么提示吗?不幸的是,我还不能使用执行器来显示配置属性,因为这是一个非 Web 应用程序。 我在 Spring Boot 1.2.2 上尝试了所有这些

【问题讨论】:

  • 嗨,你不会错过@EnableConfigurationProperties注解吗?
  • 是的,我添加了注释,现在它可以工作了。但是我注意到一件奇怪的事情:FooConfig 的默认构造函数被调用了两次,然后默认值 os 更改为 .properties 文件中指定的值。你知道为什么要这样做两次吗?
  • 我认为这是因为您将 FooConfig 声明为 Component 和 ConfigurationProperties。只保留 ConfigurationProperties 就足够了。
  • 是的,就是这样。谢谢。
  • 您能否创建一个“真实答案”,我无法接受您的 cmets 作为正确答案,我希望您的答案应得的荣誉。

标签: java spring annotations spring-boot configuration-files


【解决方案1】:

为了制作

@ConfigurationProperties(prefix = "foo")

注解工作,你的spring boot应用必须有

@EnableConfigurationProperties

注释集。

ConfigurationProperties bean 上无需设置 @Component 注解。

【讨论】:

  • 如果使用SpringBoot默认设置@EnableConfigurationProperties
猜你喜欢
  • 2021-07-14
  • 2014-12-12
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多