Spring应用程序错误:应至少有1个Bean符合此依赖关系的自动连接候选项的条件

eufgjt7s  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(161)

我得到这个错误时,我试图纳入一个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: {}

m2xkgtsf

m2xkgtsf1#

这个错误是由CustomLogger组件引起的。通过将这个类注解为@Component,Spring正在尝试创建bean,但是没有一个值可以注入到构造函数中。既然你将这个值定义为一个属性,那么修改你的CustomLogger组件如下所示:

@Component
public class CustomLogger {
  @Value("${my-env}")
  private String env;

  public CustomLogger() {}
}

或者,由于您还在配置类中构造此bean,因此只需从CustomLogger中删除@Component

相关问题