@ConditionalOnProperty注释在spring boot项目中不起作用

时间:2018-06-12 04:09:29

标签: java spring spring-boot

我想有条件地创建一个spring bean。我认为@ConditionalOnProperty会达到这个目的。我在我的服务类中使用它,但我没有看到bean被创建。

这是我想要有条件创建的bean

@Service
@ConditionalOnProperty(value = "polling.enabled", havingValue = "true")
public class MessageQueueService {

@Scheduled(fixedDelay = INTERVAL_MS)
    public void execute() {
     //sysout
    }
}

需要注意的几件事。

- 我们的服务直接从领事加载属性(由于遗留原因)而不是通过弹簧环境

- 我攻击了RestTemplate bean(下面),将自定义propertyResource添加到环境中。如果不创建另一个PropertySource bean实例,我不知道该怎么做。

@Configuration
public class AppConfig {

@Autowired
ConfigurableEnvironment env;

@Bean(name = "consulProps")
 public Properties properties() {
     Properties consulProperties = new ConsulDriver(env.getConsulUrl()).loadProperties();
    return properties;
 }

@Bean
@Autowired
public RestTemplate restTemplate(@Qualifier(consulProps) Properties props) {
    MutablePropertySources sources = env.getPropertySources();
    sources.addFirst(pollingEnabled(props));
    return new RestTemplate();
    }

private MapPropertySource pollingEnabled(Properties props) {
     String enabled = props.getProperty("polling.enabled"); // line 25
     Map<String, Object> map = new HashMap<>();
     if (StringUtils.isNotBlank(enabled)) {
           map.put("polling.enabled", enabled);
     }
     else {
          map.put("polling.enabled", "false");
     }
       return new MapPropertySource("polling", map);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

当我运行该服务时,它启动。我在领事中设置polling.enabledtrue。在调试时,我确认在第25行中正确设置了值。但是,没有创建bean。 如果我从类中注释掉@ConditionalOnProperty,则会创建bean并调用计划的方法。

任何帮助解决这个问题的人都非常感谢!! 提前致谢

0 个答案:

没有答案
相关问题