下一种情况是:Connection manager
每次都应该有一个ConnectionServer
对象和新的DataBean
对象,因此,我已经创建了这些bean,并将其配置为spring 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">
<bean id="dataBena" class="com.test.DataBean" scope="prototype"/>
<bean id="servCon" class="com.test.ServerCon"/>
<!--<bean id="test" class="com.test.Test"/>-->
<context:component-scan base-package="com.test"/>
</beans>
并为DataBean
添加了作用域prototype
之后,我创建了一个名为Test的简单util/组件类
@Component
public class Test {
@Autowired
private DataBean bean;
@Autowired
private ServerCon server;
public DataBean getBean() {
return bean.clone();
}
public ServerCon getServer() {
return server;
}
}
但是,每次调用getBean()方法时,我都在克隆这个bean,这对我来说是个问题。我可以在不使用克隆方法的情况下从spring配置中完成吗?谢谢。
发布于 2011-08-10 19:56:15
您正在寻找Spring中的lookup method功能。我们的想法是提供一个抽象的方法,如下所示:
@Component
public abstract class Test {
public abstract DataBean getBean();
}
并告诉Spring它应该在运行时实现它:
<bean id="test" class="com.test.Test">
<lookup-method name="getBean" bean="dataBean"/>
</bean>
现在,每次调用Test.getBean
时,实际上都会调用Spring生成的方法。此方法将向ApplicationContext
请求DataBean
实例。如果此bean是prototype
-scoped,则每次调用它时都会获得新实例。
我写了关于这个特性的here。
https://stackoverflow.com/questions/7010323
复制相似问题