Bean的自动装配
自动装配是Spring满足bean依赖的一种方式
Spring会在上下文自动寻找,并自动给bean装配属性。
在spring中有三种装配的方式
1.xml中显示配置
2.在java中显示配置
3.隐式的自动装配
beans.xml
<bean id="cat" class="com.haoqi.pojo.Cat"></bean> <bean id="dog" class="com.haoqi.pojo.Dog"></bean> <!-- byName 会自动在容器上下文中查找,和自己对象set方法后面的beanid --> <bean id="person" class="com.haoqi.pojo.Person" autowire="byName"> <property name="name" value="小明"></property> <property name="age" value="18"></property> </bean>
<!-- byType 会自动在容器上下文中查找,和自己对象属性相同的bean -->
<bean id="person" class="com.haoqi.pojo.Person" autowire="byType">
<property name="name" value="小明"></property>
<property name="age" value="18"></property>
</bean>
使用注解实现自动分配
配置注解@Autowried的地址:Annotation-based Container Configuration :: Spring Framework
1.
xml的配置(导入context的约束)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解的支持-->
<context:annotation-config/>
<bean id="cat" class="com.haoqi.pojo.Cat"></bean>
<bean id="dog" class="com.haoqi.pojo.Dog"></bean>
<bean id="person" class="com.haoqi.pojo.Person"></bean>
</beans>
2.pojo包中的Person类
public class Person { @Autowired private Cat cat; @Autowired private Dog dog; private String name; private int age; }
@Nullable的使用说明
// @Nullable 字段标记的这个注解说明可以为null public void setCat(@Nullable Cat cat) { this.cat = cat; }
required=false
public class Person { //如果显示定义了Autowired的required属性为false,说明这个对象可以为null.否则则不允许为空 @Autowired(required = false) private Cat cat; @Autowired private Dog dog; private String name; private int age; }
@Qualifier的使用说明
<bean id="dog111" class="com.haoqi.pojo.Dog"></bean> <bean id="dog11" class="com.haoqi.pojo.Dog"></bean>
@Autowired @Qualifier(value = "dog11") private Dog dog;
Qualifier用于选定bean对象的某一个!!!
@Resource的使用说明
public class Person { @Resource private Cat cat; @Resource private Dog dog; private String name; private int age; }
@Autowired
直接在属性上使用,也可以在set方式上使用
使用Autowired 我们可以不用编写set方法,前提是自动装配的属性是在IOC(Spring)容器中
总结:
@Resource和@Autowired的区别:
都是用来自动装配的,都可以放在属性字段上
@Autowired通过byType的方式实现,而且必须要求对象存在!!
@Resource通过byName的方式实现,如果找不到名字则byType实现! 如果俩个都找不到就报错!
执行顺序不同:@Autowired通过byType的方式实现。@Resource通过byName的方式实现。
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术