淺析 Spring IoC - XML Bean的配置

下面是Spring IoC的 xml 配置文件:java

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- <import resource="beans2.xml"/> -->

    <bean id="userDAO" class="com.dao.impl.UserDAOImpl" />
    
    <bean id="userService" class="com.service.impl.UserServiceImpl">
        <property name="userDAO" ref="userDAO" />
    </bean>
    
    <alias name="userService" alias="userServiceAlias"/>
</beans>

    在 Spring IoC的 xml 配置文件中,<bean>標籤主要用來進行 Bean 定義; 而 <alias> 用於定義 Bean 的別名; <import> 用於導入其餘配置文件的 Bean定義,能夠放在 <beans>下任何位置,無順序關係。spring

1. Bean 的命名測試

    每個 Bean 能夠有一個或者多個 id(或稱之爲 標識符 或 名稱),第一個 id 稱之爲」標識符「,其他 id 叫作別名;這些id 在容器中必須惟一。下面有幾種方式 爲 Bean 指定 id:
spa

    (1)不指定 id,之配置必須的 全限定類名,由 IoC 容器爲其生成一個標識,必須經過 getBean (Class<T>)獲取 Bean。
code

<bean class="com.service.impl.UserServiceImpl">
    <property name="userDAO" ref="userDAO" />
</bean>

    測試代碼:xml

@Test
	public void testAddUser() throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		
		UserServiceImpl service = (UserServiceImpl) ctx.getBean(UserServiceImpl.class);
		
		User user = new User();
		user.setUsername("Olive");
		service.addUser(user);
	}

    (2)指定 id,並且 id 在  IoC 容器中惟一。代碼如開頭部分,調用以下:get

UserServiceImpl service = (UserServiceImpl) ctx.getBean("userService");

    (3)指定 name,這樣name就是標識符,必須在 IoC 容器中惟一,用法同上面的 id
io

    (4)指定 id 和 name, id就是標識符,而 name 就是別名,必須在 IoC容器中惟一。若是 id 和 name 相同, IoC容器能檢測到並消除衝突。
class

    (5)指定多個 name, 用 逗號、分號或者 空格符 分隔,第一個被用做標識符,其餘的都是別名。
test

<!-- 當指定id時,name 指定的標識符全都爲別名 -->
    <bean id="userService" name="userService,userS1,userS2" class="com.service.impl.UserServiceImpl">
        <property name="userDAO" ref="userDAO" />
    </bean>

    (6)使用 <alias> 標籤指定別名,別名也必須在 IoC 容器中惟一,代碼同文章開始的配置文件。

    從上面來看,name 或者 id 均可以做爲標識符,那麼爲何還要有兩個同時存在呢?由於當使用基於 XML 的配置元數據時,在 XML 中 id 是一個真正的XML id屬性,所以當其餘的定義來引用這個id時就體現出id的好處了,能夠利用XML解析器來驗證引用的這個id是否存在,從而更早的發現是否引用了一個不存在的bean,而使用name,則可能要在真正使用bean時才能發現引用一個不存在的bean。

相關文章
相關標籤/搜索