Spring:为每次调用get方法创建bean的新实例 [英] Spring: Create new instance of bean for each call of get method
问题描述
我有下一种情况:
连接管理器
每次都应该有一个 ConnectionServer
的对象和新的 DataBean的对象
因此,我创建了这些bean并将其配置为spring xml。
I have next situation:
Connection manager
should have each time one object of ConnectionServer
and new objects of DataBean
So, I have created these beans and configured out it 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>
并为<$ c添加范围 prototype
$ c> DataBean
and added scope prototype
for DataBean
在此之后我创建了名为Test的简单的util / component类
After this I've created simple util/component class called Test
@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配置执行此操作而不使用克隆方法吗?
谢谢。
BUT, Each time of calling getBean() method I am cloning this bean, and this is the problem to me. Can I do it from spring configuration without usning clone method? Thanks.
推荐答案
您正在寻找查找方法功能。这个想法是你提供这样的抽象方法:
You are looking for lookup method functionality in Spring. The idea is that you provide an abstract method like this:
@Component
public abstract class Test {
public abstract DataBean getBean();
}
告诉Spring它应该在运行时实现它:
And tell Spring that it should implement it at runtime:
<bean id="test" class="com.test.Test">
<lookup-method name="getBean" bean="dataBean"/>
</bean>
现在每次调用 Test.getBean
你实际上会调用Spring生成的方法。此方法将为 DataBean
实例请求 ApplicationContext
。如果这个bean是 prototype
-scoped,那么每次调用它时都会得到新实例。
Now every time you call Test.getBean
you will actually call Spring-generated method. This method will ask ApplicationContext
for DataBean
instance. If this bean is prototype
-scoped, you will get new instance each time you call it.
我写的关于此功能此处。
这篇关于Spring:为每次调用get方法创建bean的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!