这个题目有点难想!我有一个在Spring容器中初始化的bean。它加载使用Spring类加载器从文件创建对象的类。其中一些对象可能依赖于昂贵的对象,我希望这些对象在父容器中初始化。好吧,我无法用语言解释,所以让我们看一个简化的例子:
public class MainLoader {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("top-context.xml"));
ChildLoader childLoader = (ChildLoader)beanFactory.getBean("childLoader");
childLoader.loadChildAndDoSomething("message1.xml");
childLoader.loadChildAndDoSomething("message2.xml");
}
}
public class ChildLoader {
public void loadChildAndDoSomething(String childContextfile){
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(childContextfile));
ClassThatDoesStuff classThatDoesStuff = (ClassThatDoesStuff)beanFactory.getBean("classThatDoesStuff");
classThatDoesStuff.saySomething();
}
}
public class ClassThatDoesStuff {
private ReallyExpensiveService reallyExpensiveService;
private String messageStart;
public void saySomething(){
System.out.println(messageStart + reallyExpensiveService.getName());
}
// .. field setters removed for brevity
}
public class ReallyExpensiveService {
public String getName(){
return "Joe";
}
}
这些文件中包含以下豆子:
top-context.xml:
<bean id="childLoader" class="com.mark.test.ChildLoader" />
message1.xml(message2.xml类似):
<bean id="classThatDoesStuff" class="com.mark.test.ClassThatDoesStuff">
<property name="messageStart" value = "Hello! " />
<property name ="reallyExpensiveService" ref="theExpensiveserviceReference" />
</bean>
<bean id="theExpensiveserviceReference" class="com.mark.test.ReallyExpensiveService" />
当运行这些代码时,你会得到预期的结果:
Hello! Joe
Goodbye! Joe
这里唯一的问题是每次都会由Spring创建和缓存"ReallyExpensiveService"。这在日志中得到了验证。最好在MainLoader初始化时加载"ClassThatDoesStuff"类(想象它是一个接口)可能需要的任何服务。也就是说(从概念上讲),更改Spring上下文文件为:
top-context.xml:
<bean id="childLoader" class="com.mark.test.ChildLoader" />
<bean id="theExpensiveserviceReference" class="com.mark.test.ReallyExpensiveService" />
message1/2.xml
<bean id="classThatDoesStuff" class="com.mark.test.ClassThatDoesStuff"
autoWired="byType">
<property name="messageStart" value = "Hello! " />
</bean>
我意识到解决这个问题的方法是让ClassThatDoeStuff有一个服务的setter,并从Child容器中设置该值,而Child容器本身则通过主上下文进行注入。但是想象一下,如果有任意数量的服务,每个ClassThatDoesStuff实现者都使用不同的服务... 在Spring中是否有任何方法可以解决这个问题?