(一)无论是在相同或不同的XML文件,“ref” 标签可以访问一个bean,但是,对于该项目的可读性,如果引用了相同的 XML文件中声明 bean,您应该使用“local”属性。
可以直接使用
<bean id="market" class="com.yiibai.common.Market">
<property name="customer" ref="person"/ >//无论在不在同一个xml文件
</bean>
<bean id="person" class="com.yiibai.common.Person" />
(二)多个配置文件的加载:可以创建一个配置文件,将其他的配置文件导入进来
<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-2.5.xsd"> <import resource="common/Spring-Common.xml"/> <import resource="connection/Spring-Connection.xml"/> <import resource="moduleA/Spring-ModuleA.xml"/> </beans>
Bean在不同的XML文件,可以使用<ref bean="someBean"/>来引用。
File : Spring-Common.xml
<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-2.5.xsd">
<bean id="OutputHelper" class="com.sdga.output.OutputHelper">
<property name="outputGenerator" >
<ref bean="CsvOutputGenerator"/>
</property>
</bean>
</beans>
File : Spring-Output.xml
<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-2.5.xsd"> <bean id="CsvOutputGenerator" class="com.sdga.output.impl.CsvOutputGenerator" /> </beans>
在同一个XML文件中的Bean,可以使用<ref local="someBean"/>
File : Spring-Common.xml
<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-2.5.xsd">
<bean id="OutputHelper" class="com.sdga.output.OutputHelper">
<property name="outputGenerator" >
<ref local="CsvOutputGenerator"/>
</property>
</bean>
<bean id="CsvOutputGenerator" class="com.sdga.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.sdga.output.impl.JsonOutputGenerator" />
</beans>