Bean的自动装配
在spring中有三种装配的方式
1.在xml中显式的配置
2.在java中显式配置
3.隐式的自动装配
一个人有两个宠物
cat dog person
<bean id="cat" class="com.ultraBlast.pojo.Cat"/>
<bean id="dog" class="com.ultraBlast.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
byType:会自动在容器上下文中查找,和自己属性类型相同的bean
-->
<bean id="person" class="com.ultraBlast.pojo.Person" autowire="byName">
<property name="dog" ref="dog"/>
</bean>
小結:
jdk1.5支持的注解,Spring2.5开始支持注解
要使用注解须知:
<?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/>
</beans>
@Autowired
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
@Autowired是按类型自动转配的,不支持id匹配
当注入在IoC容器中该类型只有一个时,就通过byType进行装配
可以使用@Qualifier来指定装配的对象
还可以使用@Resource来进行注解
小结:
@Resource和@Autowired的区别
原文:https://www.cnblogs.com/UltraBlast/p/14604547.html