0

我有一堂课:

@Configuration
public abstract class JDBCConnFactory  {        
    @Autowired
    @Qualifier("dataSource")
    @Bean
    public SimpleJdbcOperations jdbcConnection(DataSource dataSource){
        return new SimpleJdbcTemplate(dataSource);
    }
}

我尝试在另一个类中使用bean jdbcConnection:

@Autowired
@Qualifier("jdbcConnection")
private SimpleJdbcOperations dbConn;

我得到了错误:

No qualifying bean of type [org.springframework.jdbc.core.simple.SimpleJdbcOperations] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=jdbcConnection)}

或另一个例外:

 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jdbcConnection' is defined

我的错误在哪里?为什么找不到 jdbcConnection bean?

4

2 回答 2

2

您应该@Qualifier("dataSource")正确地自动装配数据源

public SimpleJdbcOperations jdbcConnection(@Qualifier("dataSource") DataSource dataSource) { ... }


然后删除@Qualifier("jdbcConnection")并简单地使用

@Autowired
private SimpleJdbcOperations dbConn;

或在类中设置 bean 名称JDBCConnFactory并保持@Qualifier("jdbcConnection")现在的状态,如下所示:

@Configuration
public abstract class JDBCConnFactory  {        
    @Autowired
    @Bean(name = "jdbcConnection")
    public SimpleJdbcOperations jdbcConnection(@Qualifier("dataSource") DataSource dataSource){
        return new SimpleJdbcTemplate(dataSource);
    }
}


如果您有多个不同的数据源和SimpleJdbcOperations,那么第二个选项更可取。否则,我认为第一个更简单,更干净。

于 2013-06-13T22:58:42.437 回答
0

Take a look at section 5.9.3 of the spring framework reference. It covers qualifiers.

You're qualifiers do not match, thus spring can not resolve your autowiring. Try this:

@Autowired
@Qualifier("dataSource")
private SimpleJdbcOperations dbConn;
于 2013-06-13T19:24:56.553 回答