1. 程式人生 > >Spring. 通過XML裝配bean

Spring. 通過XML裝配bean

1.建立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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- ... -->
	
</beans>

2.宣告bean

<bean id="loginPanel" class="top.tanmujin.login.loginPanel" />

3.藉助構造器初始化bean

<bean id="loginPanel" class="top.tanmujin.login.loginPanel">
    <constructor-arg ref="compactDisc" />    <!--傳遞對compactDisc的引用-->
    <constructor-arg value="This is String" />    <!--傳遞一個字串-->
    <constructor-arg><null/></constructor-arg>    <!--給構造器傳遞null-->
    <constructor-arg>        <!--傳遞list-->
        <list>
            <value>1</value>
            <value>2</value>
            <value>3</value>
            <value>4</value>
        </list>
    </constructor-arg>
    <constructor-arg>        <!--傳遞list,元素為對 bean 的引用-->
        <list>
            <ref bean="bean1" />
            <ref bean="bean2" />
            <ref bean="bean3" />
            <ref bean="bean4" />
        </list>
    </constructor-arg>
    <constructor-arg>        <!--set與list區別不大-->
        <set>
            <value>1</value>
            <value>2</value>
            <value>3</value>
            <value>4</value>
        </set>
    </constructor-arg>
</bean>

 


4.為bean設定屬性

<bean id="loginPanel" class="top.tanmujin.login.loginPanel" >
    <property name="compactDisc" ref="compactDisc" />    <!--注入bean的引用-->
    <property name="artist" value="The Beatles" />        <!--注入字串-->
</bean>