我得到这个错误时,我试图纳入一个Bean和Autowired为自定义日志记录器为我的Spring项目。任何帮助将不胜感激。
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
}
错误: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: {}
1条答案
按热度按时间m2xkgtsf1#
这个错误是由
CustomLogger
组件引起的。通过将这个类注解为@Component
,Spring正在尝试创建bean,但是没有一个值可以注入到构造函数中。既然你将这个值定义为一个属性,那么修改你的CustomLogger
组件如下所示:或者,由于您还在配置类中构造此bean,因此只需从
CustomLogger
中删除@Component