美文网首页
SpringBoot Question : @Autowired

SpringBoot Question : @Autowired

作者: 七喜丶 | 来源:发表于2022-03-05 14:31 被阅读0次

    失效原因

    1.包未被扫描到
    SpringBoot项目的Bean装配默认规则是根据Application类(指项目入口类)所在的包位置从上往下扫描
    可能通过@Autowired注入的类所在包路径不在Application启动类所在的包及子包路径下

    Example:
    Application启动类在A包下,则只会扫描A包及其所有子包,如果需要自动装载的类所在包不在A及其子包下,而是在B下,则不会被扫描,自然就没法被注入!

    2. 代码中使用new关键字创建实例
    若类A中包含成员属性B, B是通过@Autowired自动注入,而类A的实例是通过new的方式产生,则B的自动注入就会失效

    解决方式

    1.添加包扫描
    在启动类中定义分别扫描两个包 ,即在@SpringBootApplication注解的类中添加:

    @ComponentScan({"A","B"}) 
    

    2.通过Spring上下文工具类获取bean

    3.可以使用@PostConstruct

    @Autowired
    //B注入失败
    B b
    
    public static A  a;
    
       @PostConstruct
       public void init() {
          A = this;
          A.b = this.b;
       }
    

    相关文章

      网友评论

          本文标题:SpringBoot Question : @Autowired

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