【问题标题】:No qualifying bean of type [....] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency没有为依赖找到符合条件的 [....] 类型的 bean:预计至少有 1 个 bean 有资格作为此依赖的自动装配候选者
【发布时间】:2015-02-02 10:59:21
【问题描述】:

最近我开始了我的 Spring 冒险之旅。但是我被奇怪的错误阻止了。在我使用 Spring Boot 进行测试时,我的代码如下所示:

package m3.watermeters.srv;

..进口...

@ComponentScan
@EnableAutoConfiguration
public class Application {

    static Logger log = Logger.getLogger(Application.class.getName());

    public static void main(String[] args) {

     ApplicationContext ctx =  new ClassPathXmlApplicationContext(new String[]{"spring-bean.xml"});

        SpringApplication.run(Application.class, args);
    }
}

还有两个最重要的类:

public class AppCfgDAO extends JdbcDaoSupport  {

    static Logger log = Logger.getLogger(AppCfgDAO.class.getName());

    public  String getGeneralOwnerName() {
        return generalOwnerName;
    }

    private  String generalOwnerName;

    public void loadCfg() {
        String SQL = "SELECT * FROM utl.cfg_dictionary";
        List<CfgItemModel> cfgItemModels = (List<CfgItemModel>) getJdbcTemplate().query(SQL, new CfgRowMapper());

        Iterator<CfgItemModel> iterator = cfgItemModels.iterator();
        while (iterator.hasNext()) {
            CfgItemModel cfgItemModel = iterator.next();
            log.info("Cfg value [" + cfgItemModel.getKey() + "=" + cfgItemModel.getValue() + "] valueType=[" + cfgItemModel.getValueType() + "]");

            if(cfgItemModel.getKey().equals("general.owner_name")) {
                generalOwnerName = cfgItemModel.getValue();
            } else {
                log.error("Configuration variable [" + cfgItemModel.getKey() + "] defined in config file is not allowed");
            }
        }
    }
}

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    public AppCfgDAO getAppCfgDAO() {
        return appCfgDAO;
    }

    @Autowired
    public void setAppCfgDAO(AppCfgDAO appCfgDAO) {
        this.appCfgDAO = appCfgDAO;
    }

    public AppCfgDAO appCfgDAO;

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        appCfgDAO.loadCfg();
        System.out.println("!!!!!!!!!!!!!!" + appCfgDAO.getGeneralOwnerName());
        return new Greeting(counter.incrementAndGet(),
                String.format(template, name));
    }
}

和春季会议。 XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:property-placeholder system-properties-mode="OVERRIDE" ignore-resource-not-found="true"
                                  location="classpath:config-default.properties, classpath:config.properties"/>


    <bean
            class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    <bean id="DataSourceBean"
          class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://${db.host}:${db.port}/${db.name}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.password}"/>
        <property name="initialSize" value="5"/>
        <property name="maxActive" value="10"/>
    </bean>


    <bean id="AppCfgDAOBean" class="m3.watermeters.srv.config.AppCfgDAO">
        <property name="dataSource" ref="DataSourceBean" />
    </bean>

    <bean id="GreetingControlerBean" class="m3.watermeters.srv.GreetingController">
    </bean>
</beans>

当我启动服务器时,我收到了这样的错误消息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void m3.watermeters.srv.GreetingController.setAppCfgDAO(m3.watermeters.srv.config.AppCfgDAO); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [m3.watermeters.srv.config.AppCfgDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)

你知道我的代码哪里出错了吗? :(

【问题讨论】:

    标签: spring spring-boot autowired


    【解决方案1】:

    这可能是因为 Spring Boot 配置类 Application 不知道您的 xml 配置。尝试通过添加 @ImportResource 注释告诉 Spring Boot 考虑您的 XML 配置:

    @ComponentScan
    @EnableAutoConfiguration
    @ImportResource("classpath:to/xml/config")
    public class Application {
       //..
    }
    

    【讨论】:

    • 它有效,但我必须删除:
    • 嗨,Michal,是的,因为您已经通过 @RestController 的注解让它知道 Spring。我建议您应该遵循单一路径,不要混淆 xml 和注释配置。基于注释的配置也有明显的趋势,因为您将获得很多好处,例如类继承。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2017-10-24
    • 2017-10-01
    相关资源
    最近更新 更多