创建dataSource bean时出错

时间:2018-05-18 04:24:40

标签: java spring spring-mvc spring-security

dataSource在这个类中定义,我在springSecurityConfig.java类中使用相同的bean,但是它给了我错误: No qualifying bean of type 'javax.sql.DataSource' available

ShoppingServletConfig.java

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = "com.project.shopping")
public class ShoppingServletConfig {
 @Primary
 @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/shopping");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

   }

SpringSecurityConfig.java

@Configuration
@EnableWebSecurity

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("dataSource")
DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .jdbcAuthentication()
    .dataSource(dataSource)
    .usersByUsernameQuery(
               "select username,password, enabled from user where user_name=?")
              .authoritiesByUsernameQuery(
               "select username, role from user_roles where user_name=?");
}
控制台中的

错误是这样的:

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springSecurityConfig':
 Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=dataSource)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate.
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=dataSource)}

1 个答案:

答案 0 :(得分:0)

我有时这样做,我强迫Spring对显式bean进行依赖管理。 配置界面作为匿名类返回:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {

@Bean
public WebSecurityConfigurerAdapter securityAdapter (DataSource dataSource) {
    return new WebSecurityConfigurerAdapter () {
        @Override
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username,password, enabled from user where user_name=?")
                .authoritiesByUsernameQuery("select username, role from user_roles where user_name=?");
      }
   }
}