Spring Boot自动配置支持JSR-330 javax.inject.Inject注释(如果在classpath可用)。我想停止此cos,因为它在CDI上使用javax.enterprise.event.Event时会抛出NPE。
之所以这样做,是因为Spring自动注册4默认为BeanPostProcessings,而AutowiredAnnotationBeanPostProcessor处理@Autowired和@Value。而且还要检查类路径以注册@Inject。
错误示例:
@Named
@ViewScoped
public class FormMB implements Serializable {
@Inject
private Event<MyEvent> myEvent;
[...]
}
引发异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type javax.enterprise.event.Event<MyEvent>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}
更深入地挖掘我发现,Spring的@Inject
将JSR-330 autowiredAnnotationTypes
注释作为AutowiredAnnotationBeanPostProcessor
包含在类路径中。
任何建议都可以阻止Spring尝试自动装配@Inject
注释,或者至少阻止他自动装配javax.enterprise.event.Event
尝试过此操作:Stackoverflow,但没有成功。
@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
所以我想重写AutowiredAnnotationBeanPostProcessor,我已经能够像这样包含我自己的BeanPostProcessor:
SpringApplication application = new SpringApplication(AppConfig.class);
application.setWebApplicationType(WebApplicationType.NONE);
MyAutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new MyAutowiredAnnotationBeanPostProcessor();
autowiredAnnotationBeanPostProcessor.setBeanFactory(application.run().getBeanFactory());