【问题标题】:How to create a custom annotation in spring boot?如何在 Spring Boot 中创建自定义注解?
【发布时间】:2019-03-15 04:27:11
【问题描述】:

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

我需要类似下面的描述:

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

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

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

Execute :

a(1) // should return '2'  

【问题讨论】:

  • @grape_mao 我在运行时有一个复杂的处理这只是一个简单的例子来描述它,我希望方法 A 自动调用方法 B 并且方法 B 应该设置方法 A 的值

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


【解决方案1】:

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

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

然后将切面组件添加到你的 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

【讨论】:

  • @Denoxus 你能解释一下@Around(value = "@annotation(anno)", argNames = "jp, anno")吗?我不太明白@annotation(anno)jp, anno是什么
  • argNames = "jp, anno" 表示我们将方法的参数命名为jpanno@annotation 表示我们用一些注释来看待方法。而anno 的类型是Delegate,它将匹配@Delegate 的方法。您可以参考 AspectJ 文档以获取更多详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2018-02-01
  • 2020-11-04
  • 2017-10-03
相关资源
最近更新 更多