通过自定义SpringBeanAutowiringInterceptor 类,可以将带有@Inject 注释的依赖项排除在自动关联之外。
要了解幕后发生的事情,请查看源代码
SpringBeanAutowiringInterceptor.java -
/**
* Actually autowire the target bean after construction/passivation.
* @param target the target bean to autowire
*/
protected void doAutowireBean(Object target) {
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
configureBeanPostProcessor(bpp, target);
bpp.setBeanFactory(getBeanFactory(target));
bpp.processInjection(target);
}
在doAutowireBean 的第一行,创建了AutowiredAnnotationBeanPostProcessor 的新实例。这里配置了一组要扫描的自动连接依赖的注解。
/**
* Create a new AutowiredAnnotationBeanPostProcessor
* for Spring's standard {@link Autowired} annotation.
* <p>Also supports JSR-330's {@link javax.inject.Inject} annotation, if available.
*/
@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.
}
}
因为,默认情况下,@Inject 注释配置为 spring 扫描标记为@Inject 的各个依赖项并尝试自动连接它们。
要排除 @Inject 带注释的依赖项,请在自定义类下方编写。
public class CustomSpringBeanAutowiringInterceptor extends SpringBeanAutowiringInterceptor {
/**
* Template method for configuring the
* {@link AutowiredAnnotationBeanPostProcessor} used for autowiring.
* @param processor the AutowiredAnnotationBeanPostProcessor to configure
* @param target the target bean to autowire with this processor
*/
protected void configureBeanPostProcessor(AutowiredAnnotationBeanPostProcessor processor, Object target) {
Set<Class> annotationsToScan = new HashSet<Class>();
annotationsToScan.add(Autowired.class);
annotationsToScan.add(Value.class);
processor.setAutowiredAnnotationTypes(annotationsToScan);
}
}
这里configureBeanPostProcessor钩子用于自定义bean后处理器,以便仅包含我们需要自动连接的那些注释。
在代码中应用这个自定义类作为拦截器后,可以实现所需的行为
@Stateless
@Interceptors(CustomSpringBeanAutowiringInterceptor.class)
@LocalBean
public class SomeClass {
@Inject
private EJBClass a;
@Autowired
private SpringComponent b;
}
如果您遇到任何问题,请在 cmets 中告知。还可以随意优化认为合适的代码,并原谅任何编译/格式问题。