Cómo crear una anotación de costumbre en la primavera de arranque?

Djamel Cr:

Estoy trabajando en un proyecto de primavera y quiero hacer la anotación.

Necesito algo parecido a la descripción siguiente:

@CustomAnnotation("b")
public int a(int value) {
  return value;
}

public int b(int value) {
  return value + 1 ;
}

--------------------------

Execute :

a(1) // should return '2'  
Dean Xu:

Se puede utilizar de aspecto. Por ejemplo, usted ha siguiente anotación

@Target(METHOD)
@Retention(RUNTIME)
public @interface Delegate {
  String value(); // this is the target method name
}

A continuación, añadir el componente aspecto en su contexto primavera

@Aspect // indicate the component is used for aspect
@Component
public class DelegateAspect {
  @Around(value = "@annotation(anno)", argNames = "jp, anno") // aspect method who have the annotation @Delegate
  public Object handle(ProceedingJoinPoint joinPoint, Delegate delegate) throws Exception {
    Object obj = joinPoint.getThis(); // get the object
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // get the origin method
    Method target = obj.getClass().getMethod(delegate.value(), method.getParameterTypes()); // get the delegate method
    return target.invoke(obj, joinPoint.getArgs()); // invoke the delegate method
  }
}

Ahora se puede usar @Delegatepara delegar métodos

@Component
public class DelegateBean {

  @Delegate("b")
  public void a(int i) {
    System.out.println("a: " + i);
  }

  public void b(int i) {
    System.out.println("b: " + i);
  }
}

Vamos a prueba

@Inject
public void init(DelegateBean a) {
  a.a(1);
  a.b(1);
}

La salida es

b: 1
b: 1

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=196641&siteId=1
Recomendado
Clasificación