1. 程式人生 > 其它 >Spring 中 IoC 自動裝配(使用註解)

Spring 中 IoC 自動裝配(使用註解)

技術標籤:Spring框架springbean

1、配置bean.xml 檔案(需要配置開啟註解

<?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"
xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"
>
<!-- 開啟註解 --> <context:annotation-config/> <bean id="people" class="com.cl.pojo.People"> <property name="name" value="小明"></property> </bean> <bean id="dog" class="com.cl.pojo.Dog"
p:id="1" p:name="大黃" />
<bean id="dogNew" class="com.cl.pojo.Dog" p:id="2" p:name="小黃" /> </beans>

注意點: 需要開啟註解配置 <context:annotation-config/>


2、編寫實體類,在實體類中使用註解,來實現自動裝配

@Data
@AllArgsConstructor
@NoArgsConstructor
public class People {

    private String name;

    /*
    @Autowired 註解:
        預設是 byType 方式,如果有多符合條件的bean, 就會自動轉換成 byName 方式,
        並且IoC容器中就必須要有一個 符合的bean 並且 id 跟這裡的屬性名相同。

    @Qualifier 註解:
        當容器中有多個符合條件的 bean 時,可以用 Quqlifier 來指定使用那個 bean
        註解中 value 中指向指定的 bean 的 id名
     */
    @Autowired
    @Qualifier(value = "dogNew")
    private Dog dog;


    /*
    @Resource 註解:
    預設是 byName 方式,不指定 name 屬性,IoC容器中就必須要有一個符合的bean
    並且 id 跟這裡的屬性名相同。
     */
    @Resource(name = "car")
    private Car car;
}


小結 autowiredresource 的區別:

  • @Autowired 預設使用 ByType 方式,如果有多符合條件的bean, 就會自動轉換成 byName 方式 ,並且IoC容器中就必須要有一個 符合的bean 並且 id 跟這裡的屬性名相同。

  • @Resource 使用 ByName 方式 ,不指定 name 屬性,IoC 容器中就必須要有一個符合的bean 並且 id 跟這裡的屬性名相同。