spring——多个applicationContext.xml配置使用

有时我们需要将不同类型的注入分解到不同功能的配置文件中,这种情况我们需要使用<import>标签来导入其他配置文件,这样才可以在IOC容器中通过这个applicationContext.xml主配置文件进行注入操作

applicationContext.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
	
	<import resource="other.xml"/>
	
	<bean id="hello" class="com.impl.HelloImpl"/>
	<bean id="run" class="com.test.TestRun">
		<property name="hellointerface" ref="hello"></property>
	</bean>
	
</beans>

other.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="hello2" class="com.impl.HelloImpl2"></bean>
	
</beans>

interface

package com.inter;

public interface HelloInterface {

	public void printHello();
}

implement

package com.impl;

import com.inter.HelloInterface;

public class HelloImpl implements HelloInterface{

	@Override
	public void printHello() {
		System.out.println("hello....");
	}

}

运行结果 

修改applicationontext中的ref这时注入的是HelloImpl2

<bean id="hello" class="com.impl.HelloImpl"/>
	<bean id="run" class="com.test.TestRun">
		<property name="hellointerface" ref="hello2"></property>
	</bean>
package com.impl;

import com.inter.HelloInterface;

public class HelloImpl2 implements HelloInterface{

	@Override
	public void printHello() {
		System.out.println("hello 2......");
	}

}

运行结果  

扫描二维码关注公众号,回复: 2906082 查看本文章

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82117766