gpt4 book ai didi

java - 创建数据源 bean 时出错

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:14 27 4
gpt4 key购买 nike

dataSource 是在此类中定义的,我在 springSecurityConfig.java 类中使用相同的 bean,但它给了我错误:没有可用的“javax.sql.DataSource”类型的合格 bean

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)}

最佳答案

我有时会这样做,强制 Spring 对显式 bean 进行依赖管理。配置接口(interface)以匿名类的形式返回:

@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=?");
}
}
}

关于java - 创建数据源 bean 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403770/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com