我认为不可能改变@Autowired
注释的行为。
但是,您可以轻松实现自己的BeanPostProcessor
并使用所有便利的 Spring 类,例如AnnotationUtils
、ReflectionUtils
等。
在一个项目中,我们需要自定义 JAX-WS 端口注入。所以我们创建了@InjectedPort
注解并实现了我们自己的InjectedPortAnnotationBeanPostProcessor
(这只是说明了自定义注入逻辑的简单性,代码本身的目的与问题无关):
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) {
// Walk through class fields and check InjectedPort annotation presence
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
@Override
public void doWith(final Field field) {
// Find InjectedPort annotation
final InjectedPort injectedPort = field.getAnnotation(InjectedPort.class);
if (injectedPort == null) {
return; // Annotation is not present
}
// Get web service class from the annotation parameter
Class<?> serviceClass = injectedPort.value();
// Find web service annotation on the specified class
WebServiceClient serviceAnnotation = AnnotationUtils.findAnnotation(serviceClass, WebServiceClient.class);
if (serviceAnnotation == null) {
throw new IllegalStateException("Missing WebService " + "annotation on '" + serviceClass + "'.");
}
// Get web service instance from the bean factory
Service service = (Service) beanFactory.getBean(serviceClass);
// Determine the name of the JAX-WS port
QName portName = new QName(service.getServiceName().getNamespaceURI(), findPortLocalName(serviceClass, field.getType()));
// Obtain the JAX-WS port
Object port = service.getPort(portName, field.getType());
// Inject the port into the target bean
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, port);
}
});
return bean;
}