@Autowired注解不生效,注入的DataSource等对象值均为null如何解决
排查解决步骤
1. 检查Spring注解驱动配置是否开启
- XML配置文件里必须添加
<context:annotation-config/>或者<context:component-scan/>配置,前者开启注解注入支持,后者会自动扫描指定包下的@Component等注解,同时默认开启注解驱动功能。
注意如果只加了
<context:component-scan>,要检查base-package属性是否包含了你写的带@Component的类所在的包,包路径写错会导致类没被Spring识别托管,自然不会注入依赖。
2. 检查DataSource Bean的定义是否正确
- 确认XML里的DataSource Bean id/name没有拼写错误,Bean的
class属性是正确的数据源实现类(比如com.alibaba.druid.pool.DruidDataSource或者Spring自带的org.springframework.jdbc.datasource.DriverManagerDataSource)
3. 检查实例化类的方式是否正确
- 所有需要Spring注入依赖的类,必须是从Spring容器中获取的实例,不能自己
new出来。如果你是直接用new MyComponent()创建的对象,这个对象不会被Spring管理,@Autowired自然不会生效,所有注入的属性都是null。
正确获取实例的方式:从ApplicationContext里用
getBean(MyComponent.class)获取,或者在其他Spring托管的Bean里注入这个类的实例直接使用。
4. 检查类的注解是否正确
- 确认要注入DataSource的类上的注解是Spring的
org.springframework.stereotype.Component,不是其他框架的同名注解。如果是Controller、Service、Dao层的类,也可以对应使用@Controller、@Service、@Repository注解,效果和@Component一致。 - 检查
@Autowired注解的包是否正确,是org.springframework.beans.factory.annotation.Autowired,不是其他框架的注入注解。
5. 检查配置文件是否被正确加载
- 确认你的项目启动时已经加载了配置DataSource的XML文件:
- 如果是web项目,检查web.xml里的
ContextLoaderListener配置的contextConfigLocation是否包含了该XML路径 - 如果是普通Java项目,检查创建ApplicationContext时是否传入了该XML的路径,比如
new ClassPathXmlApplicationContext("spring-datasource.xml")
- 如果是web项目,检查web.xml里的
6. 临时验证方法
你可以在项目启动后加一段代码验证容器内的Bean情况:
// 拿到Spring上下文对象后执行 DataSource dataSource = applicationContext.getBean(DataSource.class); System.out.println("容器中获取的DataSource是否为null:" + (dataSource == null)); MyComponent myComponent = applicationContext.getBean(MyComponent.class); System.out.println("容器中获取的组件注入的DataSource是否为null:" + (myComponent.getDataSource() == null));
如果第一段输出为true,说明DataSource没有被正确注册到Spring容器,优先排查XML配置和配置文件加载问题;如果第一段为false第二段为true,说明你的组件类没有被Spring正确托管,优先排查包扫描和注解问题。
内容的提问来源于stack exchange,提问作者priya
相关产品推荐
相关产品推荐

