解决SpringBoot启动提示:is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

发现SpringBoot启动时,打印了这样的日志:

2021-10-13 17:20:47.549 [main] INFO  ... Bean 'xxx' of type [xxx] 
is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

这是由于某一个service实现了BeanPostProcessor接口,同时这个Service又依赖其他的Service导致的。例子如下:

@Service
public
class RandomIntProcessor implements BeanPostProcessor {

@Autowired
private RandomIntGenerator randomIntGenerator; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { RandomInt injectRandomInt = field.getAnnotation(RandomInt.class); if (injectRandomInt != null) { int min = injectRandomInt.min(); int max = injectRandomInt.max(); int randomValue = randomIntGenerator.generate(min, max); field.setAccessible(true); ReflectionUtils.setField(field, bean, randomValue); } } return bean; } }

其中RandomIntProcessor类依赖了RandomIntGenerator类,会导致RandomIntProcessor.postProcessBeforeInitialization方法无法接收到RandomIntGenerator初始化事件。

可修改为如下:

@Service
public
class RandomIntProcessor implements BeanPostProcessor {
private final RandomIntGenerator randomIntGenerator; @Lazy public RandomIntProcessor(RandomIntGenerator randomIntGenerator) { this.randomIntGenerator = randomIntGenerator; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //... } }

使用Lazy注解延迟初始化,打破循环依赖关系。

再启动测试,不会再输出之前的提示信息。

解决办法参考自: https://www.baeldung.com/spring-not-eligible-for-auto-proxying

原文地址:https://www.cnblogs.com/feng-gamer/p/15403339.html