javaspringspring-bootdependency-injectionconstructor-injection

Unsatisfied dependency expressed through constructor


I have a logging configuration class , from there am injecting a logging filter class to the application.I need to pass 2 string arguments to the logging filter class constructor.But its failing with error

  "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: {}"

Logging Configuration class

    @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);
    }
}

This is my logging Filter class

 @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;
    }
    }

How can i pass these variables into the filter class ?


Solution

  • The error message shows that it cannot create the @Component annotated bean since there is no bean of type String in the context that can be injected. You have two options: either providing the two missing constructor arguments as beans or to provide LoggingFilter as a bean via @Bean-annotation. Since you do aready provide a bean of type LoggingFilter in LoggingConfiguration you proceed as follows:

    You try to create the bean twice, once via @Bean and once via @Component. Please remove @Component annotation in LoggingFilter and move @Order(Ordered.HIGHEST_PRECEDENCE) to the @Bean annotated method.