@Autowired详解

请直接看原文:

@Autowired注解详解——超详细易懂-CSDN博客

-------------------------------------------------------------------------------------------------------------------------------- 

一.@Autowired详解

要搞明白@Autowired注解就是要了解它是什么?有什么作用?怎么用?为什么?

  • 首先了解一下IOC操作Bean管理,bean管理是指(1)spring创建对象 (2)spring注入属性。当我们在将一个类上标注@Service或者@Controller或@Component或@Repository注解之后,spring的组件扫描就会自动发现它,并且会将其初始化为spring应用上下文中的bean。 而且初始化是根据无参构造函数。先看代码来体会一下这个注解的作用,测试代码如下:(@Data注解是由Lombok库提供的,会生成getter、setter以及equals()、hashCode()、toString()等方法)
@Data
@Service
public class AutoWiredBean {
    private int id;
    private String name;

    public AutoWiredBean(){
        System.out.println("无参构造函数");
    }

    public AutoWiredBean(int id, String name) {
        this.id = id;
        this.name = name;
        System.out.println("有参构造函数");
    }
}

在springboot项目的测试类中进行测试,代码如下

@SpringBootTest
@RunWith(SpringRunner.class)
class Springboot02WebApplicationTests {


    private AutoWiredBean autoWiredBean;

    @Autowired
    public Springboot02WebApplicationTests (AutoWiredBean autoWiredBean){
        this.autoWiredBean = autoWiredBean;
    }

    @Test
    void contextLoads() {
    	System.out.println(autoWiredBean);
        System.out.println(autoWiredBean.getId());  //0
        System.out.println(autoWiredBean.getName());    //null
       
    }

}

控制台输出的结果如下:在这里插入图片描述

将下面代码注释了在运行

 /* @Autowired
    public Springboot02WebApplicationTests (AutoWiredBean autoWiredBean){
        this.autoWiredBean = autoWiredBean;
    }*/

输出结果如下:在这里插入图片描述
从这我们可以看到

1.无论有没有使用AutoWiredBean 类,它都被spring通过无参构造函数初始化了。当将被使用时才会创建。就对应了Spring在启动时,默认会立即调用单实例bean的空参构造方法创建bean的对象,并加载到Spring容器中。

2.不用@Autowired的private AutoWiredBean autoWiredBean值为null; 用了@Autowired的private AutoWiredBean autoWiredBean值为真实存在的AutoWiredBean类的对象;


二.有什么用

给对象类型的属性赋值(就是将本来为null的private AutoWiredBean autoWiredBean值赋值为真实存在的AutoWiredBean类的对象),可以用在成员变量、成员方法、构造方法上.

@Autowired 注解注入时首先根据byType注入,当接口存在多个实现类且使用@Service注解的默认bean名字时,根据byName注入。

@Service注解默认bean名字是小写开头的非限定(non-qualified)类名.

如果出现多个实现类可以通过 @Service("userServiceA") 来指定bean名,此时使用@Autowired需要配合@Qualifier("userServiceA")使用.

三.注意:

@Autowired 注解不能用在静态变量和静态方法上,  是因为静态变量和静态方法属于类加载期间,

而@Autowired属于spring上下文容器期间,  spring上下文容器期间只是创建类的对象,并不能对属于类的静态变量和静态方法进行操作, 因此,@Autowired加在静态变量和静态方法是无效的,并不能完成赋值功能.

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值