问题描述
我有一个声明有注解@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 bean并找到另一种解决方法(逐个销毁它们).我认为,您可以实现一个单独的管理器类,对您的容器执行操作.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!