Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring register objects destroy method

Tags:

java

spring

I'm currently converting XML spring config to Java annotations, and I've ran into a little bit of an annoying situation.

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

I can't think how to do this without creating 9 beans in java (which is fine, but it seems a little bit wrong to be polluting the class like this)

In XML config it looks something 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>
like image 425
Kehaar Avatar asked May 30 '26 00:05

Kehaar


1 Answers

One solution would be:

@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 reference documentation:

The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.

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

like image 103
Apokralipsa Avatar answered Jun 01 '26 15:06

Apokralipsa