I am getting this error when I am trying to incorporate a Bean and Autowired for a custom logger for my spring project. Any help would be appreciated.
CustomLogger.java:
@Component
public class CustomLogger {
public CustomLogger(String env) {}
}
// ... public void methods here
LoggerConfig.java:
@Configuration
public class LoggerConfig {
@Value("${my-env}")
String env;
@Bean
public CustomLogger myLogger {
return new CustomLogger(env);
}
}
Controller.java:
@RestController
public class Controller {
@Autowired private CustomLogger myLogger; // Trying to inject object created in LoggerConfig class
// GET mappings
}
Error:
Unsatisified dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Stirng' available: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
>Solution :
This error is caused by the CustomLogger component. By annotating this class as @Component, Spring is trying to create the bean but doesn’t have a value it can inject in the constructor. Since it appears that you have this value defined as a property, modify your CustomLogger component to look like this:
@Component
public class CustomLogger {
@Value("${my-env}")
private String env;
public CustomLogger() {}
}
Or, since you’re also constructing this bean in a configuration class, just drop @Component from CustomLogger