Spring: Create new instance of bean for each call of get method

Sergii Zagriichuk picture Sergii Zagriichuk · Aug 10, 2011 · Viewed 37k times · Source

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>

and added scope prototype for DataBean

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;
    }

}

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.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Aug 10, 2011

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();
}

And tell Spring that it should implement it at runtime:

<bean id="test" class="com.test.Test">
  <lookup-method name="getBean" bean="dataBean"/>
</bean>

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.

I wrote about this feature here.