首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring:为每次调用get方法创建新的bean实例

Spring:为每次调用get方法创建新的bean实例
EN

Stack Overflow用户
提问于 2011-08-10 19:51:07
回答 1查看 37.8K关注 0票数 17

下一种情况是:Connection manager每次都应该有一个ConnectionServer对象和新的DataBean对象,因此,我已经创建了这些bean,并将其配置为spring xml。

代码语言:javascript
复制
<?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/组件类

代码语言:javascript
复制
@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配置中完成吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-10 19:56:15

您正在寻找Spring中的lookup method功能。我们的想法是提供一个抽象的方法,如下所示:

代码语言:javascript
复制
@Component
public abstract class Test {
  public abstract DataBean getBean();
}

并告诉Spring它应该在运行时实现它:

代码语言:javascript
复制
<bean id="test" class="com.test.Test">
  <lookup-method name="getBean" bean="dataBean"/>
</bean>

现在,每次调用Test.getBean时,实际上都会调用Spring生成的方法。此方法将向ApplicationContext请求DataBean实例。如果此bean是prototype-scoped,则每次调用它时都会获得新实例。

我写了关于这个特性的here

票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7010323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档