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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52737181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:36:14  来源:igfitidea点击:

How to create a custom annotation in spring boot?

javaspring-mvcspring-bootannotationsspring-annotations

提问by Djamel Kr

i'm working on a spring project and i want to make annotation.

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

I need something like the description below :

我需要类似下面的描述:

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

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

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

Execute :

a(1) // should return '2'  

采纳答案by Dean Xu

You can use Aspect. For example, you have following annotation

您可以使用方面。例如,您有以下注释

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

Then add the aspect component into your spring context

然后将方面组件添加到您的 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
  }
}

Now you can use @Delegateto delegate methods

现在您可以使用@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);
  }
}

Let's test

让我们测试

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

Output is

输出是

b: 1
b: 1