问题与@ConditionalOnProperty

时间:2017-06-22 09:08:46

标签: spring spring-boot spring-integration

我需要一些帮助来理解Spring引导中对@ConditionalOnProperty的使用。我的要求是使用@@ Scheduled annotation仅在一个节点上启动cron作业。我正在使用节点IP

以编程方式设置系统属性
@Component("interation")
 public class IntegrationConfiguration {

private @Value("${integration.prinarynode}") 
String PRIMARY_NODE ;

private final Logger log = LoggerFactory.getLogger(IntegrationConfiguration.class);
@PostConstruct
   public void setProperty() {
    String ip = null;
    try {
        ip = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    log.debug("Primary Nod:"+PRIMARY_NODE);
      if(PRIMARY_NODE == null || ip.equals(PRIMARY_NODE))
      {
          log.debug("Setting integrations true");
          System.setProperty("exception.clearance.allowed", "true");
      } else {
          System.setProperty("exception.clearance.allowed", "false");
      }
   }
}

和我的预定代码

@DependsOn ({"integration"})
@Component
@ConditionalOnProperty(prefix = "exception.clearance", name="allowed", matchIfMissing = false)
public class ScheduledTasks {

    private final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    /** The services. */

    @Autowired
    // this is to 
    private IntegrationConfiguration intConfig;



    @Scheduled(fixedRate = 5000)

    public void ExceptionClear() {
        log.debug("in the sc task");

    }

}

方法ExceptionClear是cron方法,它只能在一个节点上执行

1 个答案:

答案 0 :(得分:0)

实际上,在 ScheduledTasks bean初始化之后设置属性@PostConstruct中的变化是徒劳的。

相反,我建议添加您自己的PropertyCondition

public class PropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return ... place your root detecting logic here ...
    }
}

并使用它来注释类

@Conditional(PropertyCondition.class)