java - 如何在 spring boot 中创建自定义注解?

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

我正在做一个 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
}

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

关于java - 如何在 spring boot 中创建自定义注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52737181/

相关文章:

java - 需要帮助让两个类互相帮助

java - 在引用管理表 hibernate 的用户表上插入值 1

java - 将变量存储在数组中

spring-boot - 用户角色 Spring Data Rest Spring security

java - 有没有办法根据 Activity 配置文件不启动 spring boot 应用程序?

Spring Boot 安全 CORS

java - 尝试将自定义字体应用于按钮时出现 NullPointerException

java - Spring AOP && MVC 的排序方面

java - Spring Maven - 无法加载ApplicationContext NoSuchBeanDefinitionException : No qualifying bean of type

java - jdbcTemplate 为 null 并抛出空指针异常