0

Can I keep a reference to an exposed bean inside the @Configuration class so that I can later on execute operations on that same bean? For example:

@Configuration
class MyBeanConfiguration extends DisposableBean {
  private MyBean myBean; // Correct?

  @Bean
  public MyBean myBean() {
    return (this.myBean = MyBeanFactory.newMyBean());
  }

  @Override
  public void destroy() throws Exception {
    doSomethingWith(myBean);
  }
}

Will I run into any trouble with this approach?

Dave L.
  • 9,595
  • 7
  • 43
  • 69
Roy Stark
  • 463
  • 2
  • 15

2 Answers2

0

You likely would run into trouble. Probably you don't want your Configuration class to extend DisposableBean, but rather have MyBean extend it and implement the destroy method in MyBean.

Alternately, you could configure a custom destroy method for MyBean like so: @Bean(destroyMethod='mydestroy') and that way MyBean class wouldn't have a hard dependency on Spring.

A third option would be to create a listener than implements ApplicationListener<ContextClosed> and autowire MyBean into that class and do something with it there.

Dave L.
  • 9,595
  • 7
  • 43
  • 69
  • What trouble is he likely to run into? – meriton Jul 07 '15 at 18:21
  • @meriton -- Well when would the `destroy` method get called in his original code example? Probably only when the application context is destroyed, not when the `Bean` itself is destroyed. Also, `Configuration` classes should be used as classes that *declare* beans not as beans themselves I think. – Dave L. Jul 07 '15 at 18:35
0

I sometimes do the following without any issues:

@Configuration
class MyBeanConfiguration implements DisposableBean {

  private @Autowired MyBean myBean;

  @Bean
  public MyBean myBean() {
    return MyBeanFactory.newMyBean();
  }

  @Override
  public void destroy() throws Exception {
    doSomethingWith(myBean);
  }

}

Note: I don't know if this is a bad approach, and I only do this when I am not in control of the MyBean class and cannot implement DisposeableBean there.

ESala
  • 6,878
  • 4
  • 34
  • 55