天天看點

030_bean的自動裝配

目錄

  • Spring中Bean的三種裝配方式
    • 在xml中顯式配置
    • 在java中顯式配置
    • 隐式的自動裝配
  • 使用xml配置實作自動裝配
    • byName 會自動在容器上下文中查找和set方法值名稱相同的id的bean
    • byType 會自動在容器上下文中查找和屬性類型相同的bean
  • 使用注解實作自動裝配
    • 導入限制
    • 開啟注解支援 context:annotation-config/
    • @Autowired
    • @Resource
    • @Autowired和@Resource的差別

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

<bean id="person" class="com.qing.pojo.Person" autowire="byName">
  <property name="name" value="張三豐"/>
</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>
           

直接在屬性上使用即可,也可以在set方法上使用

@Autowired
private Cat cat;