springcloud 启动包错:
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'eurekaAutoServiceRegistration': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
springclou的版本:
Dalston.RELEASE
原因分析及解决方案参考:
链接
原因:
销毁顺序问题。
根本原因是关闭ApplicationContext时,Spring将销毁所有单例 bean,首先销毁eurekaAutoServiceRegistion,然后销毁feignContext。当销毁 feignContext 时,同时销毁所有与之关联的 FeignClient。由于 eurekaAutoServiceRegistration 监听ContextClosedEvent,这些事件将被发送到该bean。不幸的是,因为它已经被销毁了,所以出现上面的异常(尝试在销毁中创建bean)。
解决方案:
作为权宜之计,调整一下销毁顺序。通过 BeanFactoryPostProcessor 改变一下依赖关系,进而影响销毁顺序。
代码如下:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class FeignBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (containsBeanDefinition(beanFactory, "feignContext", "eurekaAutoServiceRegistration")) {
/* 调整依赖顺序,这样会先销毁 feignContext, 再销毁 eurekaAutoServiceRegistration */
BeanDefinition bd = beanFactory.getBeanDefinition("feignContext");
bd.setDependsOn("eurekaAutoServiceRegistration");
}
}
private boolean containsBeanDefinition(ConfigurableListableBeanFactory beanFactory, String... beans) {
return Arrays.stream(beans).allMatch(b -> beanFactory.containsBeanDefinition(b));
}
}
总结:
换个比D版本的springcloud高的springcloud版本就可以解决了