Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom annotation in spring boot?

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

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'  
like image 399
Djamel Kr Avatar asked Oct 10 '18 09:10

Djamel Kr


People also ask

Can we create custom annotation in spring boot?

In this way, we can create different custom annotations for validation purposes. You can find the full source code here. It is easy to create and use custom annotations in Java. Java developers will be relieved of redundant code by using custom annotations.


1 Answers

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

@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 @Delegate to delegate methods

@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
like image 179
Dean Xu Avatar answered Oct 04 '22 20:10

Dean Xu