You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目中无法自动装配DataSource问题求助

解决Spring Security配置中DataSource无法自动装配的问题

嘿,我一眼就瞅到你这问题的关键所在了——明明之前数据库能正常存数据,怎么到Security配置里就找不到DataSource Bean了呢?咱们一步步理清楚:

问题核心:注解用错地方了

你的SecurityConfig类上多了个@RequestMapping("cheese")注解!这个注解是给Controller用的,用来映射请求路径,你把它加在Security配置类上,会让Spring把这个类当成Controller组件来处理,而不是Spring Security的配置类。这种角色混乱直接导致依赖注入机制没法把DataSource Bean正确绑定到这个类里,哪怕你能导入javax.sql.DataSource也没用。

快速修复步骤

1. 移除错误的注解

把SecurityConfig上的@RequestMapping("cheese")删掉,这个注解只需要留在你的UserController上就行。修改后的配置类头部应该是这样:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 剩余代码保持不变
}

2. 确认依赖没缺漏

虽然你之前能正常持久化数据,但还是要确保pom.xml里有必要的JDBC依赖。如果你用的是Spring Data JPA,spring-boot-starter-data-jpa已经包含了spring-boot-starter-jdbc,但如果没引入的话,手动加一下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

3. 补全数据源配置(可选)

你的application.properties配置基本没问题,要是MySQL版本是8.0+,可以显式指定驱动类,避免自动识别出错:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

额外提醒:密码加密不能忘

看到你在usersByUsernameQuery里直接返回明文密码,这在生产环境绝对不行!赶紧加个密码编码器:

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

然后在认证配置里关联上:

auth.jdbcAuthentication()
    .dataSource(dataSource)
    .usersByUsernameQuery("select email as principal, password as credentials, true from user where email=?")
    .passwordEncoder(passwordEncoder());

注册用户的时候也要用这个编码器加密密码,比如在UserController里:

customer.setPassword(passwordEncoder.encode(customer.getPassword()));
customerDao.save(customer);

总结

归根到底就是SecurityConfig上的@RequestMapping注解搞的鬼,去掉它之后,Spring会正确把这个类当成Security配置类处理,DataSource就能正常注入了。

内容的提问来源于stack exchange,提问作者user2411290

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:43:01