發現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注解延遲初始化,打破循環依賴關系。