0

いくつかの条件またはパラメーターで機能するカスタム スプリング アノテーションを作成したいと考えています。しかし、ビジネス上の制約として、Genre アノテーションを持つライブラリをすべてのアプリケーションで共有する必要があります。@Profile アノテーションなどの一部のアプリケーションに制限するようにアノテーションを構成することはできますか?

@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Genre {
  String value();
}

とその使い方

public class MovieRecommender {
@Autowired

   @Genre("Action")
   private MovieCatalog actionCatalog; 

   private MovieCatalog comedyCatalog;

   @Autowired
   public void setComedyCatalog(@Genre("Comedy") MovieCatalog comedyCatalog) { 
      this.comedyCatalog = comedyCatalog;
   }
// ...
}
4

1 に答える 1

0

@Autowired注釈の動作を変更することはできないと思います。

ただし、独自のものを簡単に実装して、 、BeanPostProcessorなどのすべての便利な Spring クラスを使用できます。AnnotationUtilsReflectionUtils

あるプロジェクトでは、カスタム 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;
}
于 2013-06-20T15:00:44.420 に答える