IDEA提示Field injection is not recommended 之Spring 3种注入bean的方式

1.变量注入:

class A {
    @Autowired
    private Bean bean;
}

2.构造器注入:

class A {
    
    private Bean bean;
    @Autowired
    public A(Bean bean) {
         this.bean = bean;
    }
}

 

3.方法注入:

class A {
    
    private Bean bean;
    @Autowired
    public autowired(Bean bean) {
         this.bean = bean;
    }
}

 

三种注入方式的特点和使用场景:

1.应该避免字段注入,因为对象不能独立于容器运行(也就是说,如果对象不在容器中,容器启动时会报错,但是我还是大量使用字段注入,因为方便 -_-!)。

2.构造函数注入用于强制对象注入(编译时就会检查是否存在Bean)。

3.方法注入适用于注入可选对象。

 

 

 

 
posted @ 2022-02-16 10:44  芬尼克斯  阅读(393)  评论(0编辑  收藏  举报