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

Ser*_*huk 16 java spring cloning

我有下一种情况: Connection manager应该每次都有一个对象ConnectionServer和新对象的DataBean So,我已经创建了这些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>
Run Code Online (Sandbox Code Playgroud)

并添加范围prototypeDataBean

在此之后,我创建了名为Test的简单util/component类

@Component
public class Test {

    @Autowired
    private DataBean bean;
    @Autowired
    private ServerCon server;

    public DataBean getBean() {
        return bean.clone();
    }

    public ServerCon getServer() {
        return server;
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,每次调用getBean()方法我都会克隆这个bean,这对我来说是个问题.我可以在没有克隆方法的情况下从spring配置中做到吗?谢谢.

Tom*_*icz 33

您正在寻找Spring中的查找方法功能.想法是你提供这样的抽象方法:

@Component
public abstract class Test {
  public abstract DataBean getBean();
}
Run Code Online (Sandbox Code Playgroud)

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

<bean id="test" class="com.test.Test">
  <lookup-method name="getBean" bean="dataBean"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

现在,每次调用Test.getBean时,实际上都会调用Spring生成的方法.这种方法将要求ApplicationContextDataBean实例.如果这个bean是prototype-scoped,那么每次调用它时都会得到新的实例.

在这里写了这个功能.