發現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