java - Spring @ConditionalOnProperty 注释未按预期工作

标签 java spring spring-boot security annotations

我在属性文件中定义了一个属性:property=true

然后我有 SomeClass.java 类,如果属性 property 设置为真。

这是我的 SomeClass 类:

public class SomeClass {

  //this is the proerty which I set to true or false
  @Value("${property}")
  private String property;

  //this is the bean which needs to be created conditionally based on the property but at the moment it does not get created
  @Bean
  @ConditionalOnProperty(name="${property}", havingValue="true")
  public PropertyConfiguration propertyConfig() {
    // doesnt print anything because the bean does not get created
    System.out.print(property);
  }
}

如果我在 @ConditionalOnProperty 中添加 matchIfMissing = true,只是为了试验并查看 property 的值是多少,然后bean 确实被创建了,我看到 property 的值为 true

如果我删除 matchIfMissing = true,将条件保留为 @ConditionalOnProperty(name="${property}", havingValue="true") 并更改属性 property=truetruefalse 永远不会创建 bean(无论是 true 还是 )。

我该怎么办根据属性有条件地创建 bean?

最佳答案

请在您的类上方添加@Configuration

组件扫描不包括您的类,为此需要在您的类之上添加 @Component 或任何其他继承的注释。然后你的 @Bean 应该从 spring 创建。

希望这对您有所帮助。

关于java - Spring @ConditionalOnProperty 注释未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297465/

相关文章:

java - XJC 多个 XSD -> 使用 "episode"生成类

java - 如何基于gradle进行资源和java文件夹测试

java - spring-boot-starter-web-reactive + spring-boot-starter-actuator 不能一起工作?

java - 检查 MySQL 中的重复插入

java - Android:UsageStatsManager 未返回正确的每日结果

java - Hibernate 查询语言 (HQL) 更新列表

java - Spring Batch ItemReader使用PostgreSQL函数游标错误

java - Spring Boot 应用程序不使用 java -jar 运行

Java 类设计 - 最佳方法的建议。类扩展抽象类并实现接口(interface)

java - 如何解析作为 json 字符串 int 时间对象接收的时间 PT15H30M?