如何在 spring 引导中创建自定义注释?

How to create a custom annotation in spring boot?

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

我需要如下描述的东西:

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

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

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

Execute :

a(1) // should return '2'  

您可以使用看点。例如,您有以下注释

@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