【问题标题】:Spring: Create new instance of bean for each call of get methodSpring:为每次调用get方法创建bean的新实例
【发布时间】:2011-08-10 11:51:06
【问题描述】:

我有下一个情况: 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 的简单实用程序/组件类

@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 配置中做到这一点不使用克隆方法吗? 谢谢。

【问题讨论】:

    标签: java spring cloning


    【解决方案1】:

    您正在寻找 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

    【讨论】:

    • 只需将 cglib.jar 添加到您的 CLASSPATH 中。
    • 如果DataBean 是一个泛型,并且如果它里面有一个Service&lt;T&gt;,它是@Autowired,取决于&lt;T&gt; 类型,你将如何处理这个问题?
    • 从春天开始使用 ObjectFactory。寻找例子,网上有很多可用的。确保将 @Scope("prototype") 提供给您的班级。
    猜你喜欢
    • 2018-02-02
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多