@Autowired自动装配对象为null的问题、原因及解决方法以及ApplicationContext的getBean()方法

问题缘由
在获取某个类的时候,遇到@Autowired自动注入的值为null的情况;
但通过ApplicationContext的getBean()方法就不会为空值;
参考:Spring进阶篇(2)-ApplicationContextAware(动态获取容器中Bean)

//为空值
@Autowired
RoleLevelResourceManager roleLevelResourceManager;
//不为空值
//Context是实现ApplicationContextAware接口获取ApplicationContext上下文对象,通过getBean的方式,获取到Spring容器的Bean
RoleLevelResourceManager roleLevelResourceManager = Context.getBean(RoleLevelResourceManager.class);

于是查阅资料,了解问题。
一般无法@Autowired无法注入的情况(只针对spring):

  1. spring boot项目启动类入口要尽量放在顶级包下,spring会自动扫描子包以及子孙包的bean,基本不会存在无法注入的情况。普通spring项目配置文件配置<context:component-scan base-package=“com.springmvc.test” />等。
  2. 由于spring帮我们管理bean,容器里面的bean默认是单例的,除非自行配置scope=prototype。
    所以不能自己去new,比如new xxxService(), 这个service对象是有的,但是里面注入的属性全部是null,spring不会给new出来的对象注入属性。
@Component(value=
  • 15
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
可能出现这种情况的原因有很多,以下是一些可能的解决方案: 1. 确保在配置文件中正确配置了需要自动装配对象,例如: ``` @Configuration @PropertySource("classpath:application.properties") public class AppConfig { @Autowired private Environment env; @Bean public MyConfig myConfig() { MyConfig config = new MyConfig(); config.setUrl(env.getProperty("my.url")); config.setUsername(env.getProperty("my.username")); config.setPassword(env.getProperty("my.password")); return config; } } ``` 2. 确保配置文件的路径和文件名是正确的,例如: ``` @PropertySource("classpath:application.properties") ``` 这里的classpath表示classpath下的根目录,如果配置文件在子目录下,需要在路径中添加相应的目录。 3. 确保项目的classpath正确配置,例如: 在IDEA中,可以在项目的“Run/Debug Configurations”中查看项目的classpath,确保配置文件在classpath下。 4. 确保需要自动装配对象类上使用了@Component、@Configuration、@Service等注解,例如: ``` @Component public class MyConfig { private String url; private String username; private String password; // getter and setter methods } ``` 这里使用了@Component注解,表示这是一个Spring组件,可以被自动扫描并装配。 5. 确保使用了正确的@Autowired注解,例如: ``` @Autowired private MyConfig myConfig; ``` 这里使用了@Autowired注解,表示需要自动装配MyConfig对象。 6. 如果使用了多个配置文件,需要确保它们没有冲突,例如: ``` @PropertySources({ @PropertySource("classpath:application.properties"), @PropertySource("classpath:other.properties") }) public class AppConfig { // ... } ``` 这里使用了@PropertySources注解,可以配置多个配置文件。需要确保它们没有相同的属性名,否则会出现冲突。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值