Spring method to destroy registry objects

I am currently converting spring config XML to Java annotations and I am facing a little annoying situation.

I need to create 3 beans that use the same class internally, but need to be separate instances. However, these internal beans need to register their shutdown method with Spring.

I can't think of how to do this without creating 9 beans in java (that's ok, but it seems a bit wrong to pollute the class like this)

In XML configuration, it looks like this:

<bean class="outer1">
    <constructor-arg>
        <bean class="middle">
            <constructor-arg>
                <bean class="inner" />
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean class="outer2">
    <constructor-arg>
        <bean class="middle">
            <constructor-arg>
                <bean class="inner" />
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean class="outer3">
    <constructor-arg>
        <bean class="middle">
            <constructor-arg>
                <bean class="inner" />
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>

      

+3


source to share


1 answer


One solution:

@Configuration
public class MyConfig{
    @Bean(destroyMethod="cleanup")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Inner inner(){
        return new Inner();
    }


    @Bean(destroyMethod="cleanup")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Middle middle(){
        return new Middle(inner());
    }

    @Bean
    public Outer outer1(){
        return new Outer(middle());
    }


    @Bean
    public Outer outer2(){
        return new Outer(middle());
    }


    @Bean
    public Outer outer3(){
        return new Outer(middle());
    }
}

      

From the reference documentation :



The non-elementary, prototypal bean deployment scope results in a new bean instance being created every time a request is made for that particular bean.

This means that every call to the middle () and inner () method creates a new instance of your bean.

+4


source







All Articles