如何为使用 @Bean 注释声明的 bean 调用 @PreDestroy [英] How to call @PreDestroy for a bean declared with @Bean annotation

查看:32
本文介绍了如何为使用 @Bean 注释声明的 bean 调用 @PreDestroy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用@Bean 注释声明的 bean

I have a bean declared with annotation @Bean

@Bean
public Set<DefaultMessageListenerContainer> beans() {
    Set<DefaultMessageListenerContainer>  containerSet = new HashSet<DefaultMessageListenerContainer>();

    return containerSet;
}

我在销毁 bean 时需要执行一些操作.我怎样才能做到这一点?

I have some operations to be performed when I am destroying the bean. How can I achieve that?

我知道我可以在用@Component 注释的类中的方法上使用@predestroy 注释,但不确定在声明@Bean 注释时我该怎么做.

I know I can use @predestroy annotation on a method in a class annotated with @Component but not sure how can I do that when declared @Bean annotation.

@Bean(destroyMethod="stopContainers")
   public Set<DefaultMessageListenerContainer> containers() {
        Set<DefaultMessageListenerContainer>  containerSet = new HashSet<DefaultMessageListenerContainer>();

        return containerSet;
    }

   public void stopContainers(){
        Set<DefaultMessageListenerContainer>  containerSet = containers();
        ......
        }

    }

但是我收到一个错误,在名为containers"的 bean 上找不到名为stopContainers"的销毁方法如何解决这个问题?

But I am getting an error , Couldn't find a destroy method named 'stopContainers' on bean with name 'containers' How to fix this?

推荐答案

通常,您可以为 @Bean 注释指定 destroyMethod 参数.并在您的 bean 类中定义此方法的特定实现.

Generally you can specify destroyMethod parameter for the @Bean annotation. And define the particular implementation for this method in your bean class.

当您使用 Set 时,您没有机会将 destroyMethod 添加到 Set.class 中.所以你必须包装它(如安德鲁提议).

As you're using Set you have no chance to add destroyMethod into the Set.class. So you have to wrap it (as Andrew proposed).

实际上,我根本不喜欢这种方法.最好不要使用 Set of beans 并找到另一种解决方法(通过一个一个地销毁它们).在我看来,您可以实现一个单独的管理器类对容器执行操作.

Actually, I don't like this kind of approach at all. It seems more preferable not to use Set of beans and find another workaround (by destroying them one by one). In my opinion, you can implement a separate manager class performing operations on your containers.

这篇关于如何为使用 @Bean 注释声明的 bean 调用 @PreDestroy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆