美文网首页
Spring boot下@Autowired 注入为 NULL的

Spring boot下@Autowired 注入为 NULL的

作者: 知可及而愚不可及 | 来源:发表于2020-01-17 16:05 被阅读0次

spring boot自定义类中 @Autowired注入失败问题小记


  • 第一种方法:@PostConstruc,大多数人使用的方式,不过对于我的问题没有用
  • 第二种方法:实现ApplicationRunner接口,在run方法执行后进行初始化
  • 第三种方法:实现ApplicationContextAware接口,直接到spring容器拿bean

代码如下 shiroConfig与shiroProperties注入失败,始终为null @PostConstruct也没有执行

shiroConfig.jpg
  • 实验1
    实现ApplicationRunner 在服务完成后执行init
  • 结果:shiroConfig与shiroProperties依然为null
ApplicationRunner.jpg
  • 实验2
    实现ApplicationContextAware从spring容器中拿bean
  • 结果:
    在shiroConfig中通过ApplicationContextUtil.getBean(ShiroProperties.class);
    NPE异常、ApplicationContextUtil注入执行晚于ShiroConfig。 — — !
ApplicationContextAware.jpg
  • 到现在已经知道了是bean加载顺序的问题
  • 查资料发现springboot可以通过下面四种方式来控制bean依赖的初始化问题*
  • 1 @Order
    2 @AutoConfigureAfter
    3 @DependsOn
    4 将bean通过形参进行绑定
    发现Order与DependsOn对于我的问题无效,最后使用第四种方法:将bean通过形参进行绑定解决问题
DependsOn.jpg

配置shiro过滤链


shiroProperties.jpg

最后一点 在yml中可以通过使用[]对yml中的特殊字符进行转义

shiroYml.jpg
  • 以上均为个人理解,如有不足之处,欢迎在评论区留言

相关文章

网友评论

      本文标题:Spring boot下@Autowired 注入为 NULL的

      本文链接:https://www.haomeiwen.com/subject/xmiczctx.html