@Autowired注解详解

您所在的位置:网站首页 java中注解的作用是什么 @Autowired注解详解

@Autowired注解详解

2024-06-03 16:28| 来源: 网络整理| 查看: 265

@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; }*/

输出结果如下:在这里插入图片描述 从这我们可以看到无论有没有使用AutoWiredBean 类,它都被spring通过无参构造函数初始化了。当将被使用时才会创建。 进入正题它有什么用? @Autowired可以标注在属性上、方法上和构造器上,来完成自动装配。默认是根据属性类型,spring自动将匹配到的属性值进行注入,然后就可以使用这个属性(对Springboot02WebApplicationTests类来说)autoWiredBean对象的方法。 怎么用? 它可以标注在属性上、方法上和构造器上,那有什么区别吗?简单来说因为类成员的初始化顺序不同,静态成员 ——> 变量初始化为默认值——>构造器——>为变量赋值。如果标注在属性上,则在构造器中就不能使用这个属性(对象)的属性和方法。

推荐: 对构造函数标注注解,如图在构造器上标注@Autowired注解 在这里插入图片描述 当标注的属性是接口时,其实注入的是这个接口的实现类, 如果这个接口有多个实现类,只使用@Autowired就会报错,因为它默认是根据类型找,然后就会找到多个实现类bean,所有就不知道要注入哪个。然后它就会根据属性名去找。所以如果有多个实现类可以配合@Qualifier(value=“类名”)来使用 (是根据名称来进行注入的)可以参考 spring@Autowired注解的注入规则

有些地方可能表述不清望包涵,望指出。我会马上改正



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3