如何在Spring Boot中创建自定义注释?

时间:2018-10-10 09:41:26

标签: java spring-mvc spring-boot annotations spring-annotations

我正在做一个春季项目,我想做注释。

我需要类似下面的描述:

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

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

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

Execute :

a(1) // should return '2'  

1 个答案:

答案 0 :(得分:7)

您可以使用Aspect。例如,您具有以下注释

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

然后将Aspect组件添加到您的Spring上下文中

@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
  }
}

现在您可以使用@Delegate委托方法

@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);
  }
}

让我们测试

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

输出为

b: 1
b: 1