首页 > 解决方案 > 如何在春季启动中使用条件接口与列表中的值

问题描述

我有 application-sample.YAML 文件,其中有数据。加载数据后,基于某些字段。我想决定加载或不加载哪些组件。我可以看到下面的条件类首先加载,结果,我得到的数据为空,因为这个条件类在我的数据加载之前先加载。

@Configuration
public class AwsCondition implements Condition {
    
    @Autowired
    MyTestData data;
    
    @Override       
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // TODO Auto-generated method stub
        log.info("inside...........condition");
        if(data.getListeners().size()>1){
            return true;
        }
        return false;
    }

}

MyTestData.java

@Slf4j
@Data
@ConfigurationProperties
@Component
public class MyTestData implements InitializingBean {

List<Listener> listeners = new ArrayList<>();

    @Data
    public static class Listener {
        private String type;
        private String name;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        
        if (this.getListeners().isEmpty()) {
            log.info("Nothing  configured. Please verify application-test.yml is configured properly.");
            System.exit(1);
        }
    }
}

条件测试类

@Component
@Conditional(AwsCondition.class)
public class TestS3ListenerRouter extends RouteBuilder {
 //My all logic lying here
}

标签: springspring-bootspring-annotations

解决方案


尝试以下操作:

@Component
public class AwsCondition implements Condition {
    
    @Autowired
    MyTestData data;
    
    @Override       
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // TODO Auto-generated method stub
        log.info("inside...........condition");
        if(data.getListeners().size()>1){
            return true;
        }
        return false;
    }
}

推荐阅读