【问题标题】:Unsatisfied dependency expressed through constructor [duplicate]通过构造函数表达的不满足的依赖关系[重复]
【发布时间】:2020-05-10 11:42:39
【问题描述】:

我有一个日志配置类,从那里向应用程序注入一个日志过滤器类。我需要将 2 个字符串参数传递给日志过滤器类构造函数。但是它失败并出现错误

  "message" : "Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'LoggingFilter' defined in file \LoggingFilter.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}"

日志配置类

    @Configuration
public class LoggingConfiguration {

    @Value("${operation.name}")
    private String operationName;

    @Value("${source.name.ui}")
    private String sourceName;

    @Bean
    public LoggingFilter getLoggingFilter() {
        return new LoggingFilter (operationName,sourceName);
    }
}

这是我的日志过滤器类

 @Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LoggingFilter implements Filter {

    private String operationName;
    private String source;


    public LoggingFilter(String operationName,String source) {
        this.operationName = operationName;
        this.source = source;
    }
    }

如何将这些变量传递给过滤器类?

【问题讨论】:

    标签: java spring spring-boot dependency-injection constructor-injection


    【解决方案1】:

    错误消息显示它无法创建 @Component 注释 bean,因为上下文中没有 String 类型的 bean 可以注入。您有两个选择:要么将两个缺少的构造函数参数作为 bean 提供,要么通过 @Bean-annotation 将 LoggingFilter 作为 bean 提供。由于您确实在 LoggingConfiguration 中提供了 LoggingFilter 类型的 bean,因此请按以下步骤操作:

    您尝试创建 bean 两次,一次通过@Bean,一次通过@Component。 请去掉LoggingFilter中的@Component注解,将@Order(Ordered.HIGHEST_PRECEDENCE)移到@Bean注解的方法中。

    【讨论】:

    • @SotiriosDelimanolis 问题是“如何将这些变量传递给过滤器类?”。我展示了如何将变量传递给过滤器类的方法。
    • @SotiriosDelimanolis 我改进了我的答案。然而,由于 LoggingFilter 类型的 bean 已经在上下文中,我认为作者只是无意中添加了 @Component 注释。这就是为什么我刚刚回答删除此注释...
    • @SotiriosDelimanolis 感谢您分享您的反馈。如果一个答案只是被否决,有时很难弄清楚为什么:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2019-11-09
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多