繁体   English   中英

Spring 自动连线启动条件需要默认构造函数

[英]Spring boot condition with autowired requires a default constructor

正如问题所述,我的以下代码使用一些属性来启动一些带有 spring 引导的骆驼路线。 但这必须通过使用环境变量在骆驼路线 class 有条件地发生。


@Configuration
public class SomeCondition implements Condition {


    private final Properties properties;

    public SomeCondition(Properties properties) {
        this.properties = properties;
    }

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return properties.isEnableData();
    }
}

但是当尝试开始或运行一些测试时,我得到了错误:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [xxx.in.annotation.SomeCondition]: No default constructor found; nested exception is java.lang.NoSuchMethodException: xxx.in.annotation.SomeCondition.<init>()
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
    at org.springframework.context.annotation.ConditionEvaluator.getCondition(ConditionEvaluator.java:125)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:96)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:88)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:71)
    at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isConditionMatch(ClassPathScanningCandidateComponentProvider.java:513)
    at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isCandidateComponent(ClassPathScanningCandidateComponentProvider.java:496)
    at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.scanCandidateComponents(ClassPathScanningCandidateComponentProvider.java:430)
    ... 88 more
Caused by: java.lang.NoSuchMethodException: 
xxxx.in.annotation.SomeCondition.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3349)
    at java.base/java.lang.Class.getDeclaredConstructor(Class.java:2553)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    ... 95 more

有什么方法可以自动接线或在某种条件下注入一些东西?

ConditionalContext实例有一个 getter 方法getEnvironment() ,它也有检查属性的方法。 所以你可以在你的matches方法中调用它,而不必注入一个bean。

这与 Spring Boot 在其OnPropertyCondition class 中执行此操作的方式相同,它基本上提供了您可能需要的相同功能: Z5E056C500A1C4B6A7110B50D807BADE-spring-boot/githubb.com/spring-project/spring-boot/githubb.com//spring-project/项目/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java

附加建议:如果属性/环境变量是唯一条件,那是必要的,你实际上可以只使用 Spring Boot 提供的注解@ConditionalOnProperty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM