【bean自动装配】 本是古典 何须时尚 2024-03-22 11:15 32阅读 0赞 ### 搭建环境 ### ![03dba058e8da7db32e22c622634feeed.jpeg_pic_center][] public class People { private Cat cat; private Dog dog; private String name; } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="cat" class="com.canso.pojo.Cat"/> <bean id="dog" class="com.canso.pojo.Dog"/> <bean id="people" class="com.canso.pojo.People"> <property name="name" value="canso"/> <property name="cat" ref="cat"/> <property name="dog" ref="dog"/> </bean> </beans> ### byName / byType自动装配 ### <!--byName:自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid--> <bean id="people" class="com.canso.pojo.People" autowire="byName"/> <!--byType:自动在容器上下文中查找,和自己对象属性类型相同的bean,缺点是类型必须全局唯一--> <bean id="people" class="com.canso.pojo.People" autowire="byType"/> byName:需保证所有bean的id唯一,且和自己对象set方法后面的值一致 byType:需保证所有bean的class唯一,且和自己对象属性的类型相同 ### 注解自动装配 ### 1.导入约束 xmlns:context=“http://www.springframework.org/schema/context” 2.配置注解的支持 **context:annotation-config/** <?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** 直接在实体类的属性上使用即可,也可以在set方法上使用 使用Autowired可以不用编写set方法,前提是自动装配的属性在IOC容器中存在,并且符合名字**bytype** 由于@Autowired是利用bytype,所以当bean中有多个同类型的类而beanid不同时,单独加@Autowired的话,程序不知道指向哪一个,故可以在属性加 **@Qualifier(value=" ")** **@nullable** 字段标记了这个注释,说明该字段为null **@Resource** 首先通过byname的方式实现,若找不到,再通过bytype的方式实现, [03dba058e8da7db32e22c622634feeed.jpeg_pic_center]: https://image.dandelioncloud.cn/pgy_files/images/2024/03/22/81f98586660a467db0b8066a8776a2ea.png
还没有评论,来说两句吧...