030_bean的自动装配


Spring中Bean的三种装配方式

在xml中显式配置

在java中显式配置

隐式的自动装配

使用xml配置实现自动装配

byName 会自动在容器上下文中查找和set方法值名称相同的id的bean

<bean id="cat" class="com.qing.pojo.Cat"/>

<bean id="person" class="com.qing.pojo.Person" autowire="byName">
  <property name="name" value="张三丰"/>
</bean>

byType 会自动在容器上下文中查找和属性类型相同的bean

<bean class="com.qing.pojo.Cat"/>

<bean id="person" class="com.qing.pojo.Person" autowire="byType">
  <property name="name" value="张三丰"/>
</bean>

使用注解实现自动装配

jdk1.5开始支持注解,spring2.5开始支持注解

导入约束

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/>

<?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
private Cat cat;

image.png
image.png

@Resource

image.png

@Autowired和@Resource的区别

image.png

posted @ 2021-08-16 00:43  清风(学习-踏实)  阅读(34)  评论(0)    收藏  举报