这是可能的,即使您可以分层创建多个不同的上下文。
我会给出两个答案,包括等级和非等级。我将为两者使用基于 java 的配置。我将给出两个上下文的答案,但你可以在许多上下文中实现它。
1)非分层
创建两个不同的context.xml,假设context1.xml 和context2.xml。 context1.xml 应该是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=..... some imports >
<context:annotation-config />
<context:component-scan base-package="desiredPackage1" />
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>db.properties</value>
</list>
</property>
</bean>
<context:property-placeholder properties-ref="properties"/>
仅适用于 context2.xml 更改
<context:component-scan base-package="desiredPackage2" />
然后像这样创建一个Configuration.java 类:
public class Config {
public static void main(String[] args) throws Exception {
ApplicationContext desiredContext1 = new ClassPathXmlApplicationContext("file:////...path.../context1.xml");
ApplicationContext desiredContext2 = new ClassPathXmlApplicationContext("file:////...path.../context2.xml");
}
}
现在你有两个不同的上下文,如果你想分层,改变 main 方法如下:
2)分层
public class Config {
public static void main(String[] args) throws Exception {
ApplicationContext desiredContext1 = new ClassPathXmlApplicationContext("file:////...path.../context1.xml");
String[] congigPath = new String[1];
congigPath[0] = "file:////...path.../context2.xml";
ApplicationContext desiredContext2 = new ClassPathXmlApplicationContext(congigPath,desiredContext1);
}
}
在这种情况下,desiredContext2 对象可以看到desiredContext1 对象,但desiredContext1 对象看不到desiredContext2 对象。
如果您想在构建网络应用时使用它,请将此注释与您的配置类一起使用,
@Configuration
@ImportResource("context1.xml", "context2.xml")
public class Config { ....
希望对你有帮助。