Home > Back-end >  Get common data from Springboot AOP
Get common data from Springboot AOP

Time:10-05

I have a number of class where the first thing I have to do in the methods is retrieve the value of a variable from an external system.

class One {

  ExternalService externalService;
  public void method1() {
    var field = externalService.getValue();
    // do something with field
  }
}

class Two{

  ExternalService externalService;
  public void method2() {
    var field = externalService.getValue();
    // do something with field
  }
}

I think this functionality could extract it to an aspect and get the value of field. I have seen that you could make use of @Around. But my doubt is that once the field value is retrieved in the aspect, how do I return it to method1, method2 so that these methods can use the variable?

CodePudding user response:

Since you have not highlighted if its webapp/standalone app, I am going with webapp and my understanding.

Way 1:.

You can take help of spring bean lifecycle and do a common call to external service in @PostConstruct method. You can also explore other bean lifecycle callbacks for this purpose.

Way 2:.

There can be another way to do the same thing. You can use spring bean scopes to wire such information based on your use case.

eg: is the data going to be unique per request then you can store data in request scope

else session or application scope are also available scopes.

Credits for this brilliant idea to this answer: https://stackoverflow.com/a/41774566/1811348

Ref: https://www.baeldung.com/spring-bean-scopes

Way 3:

Also instead of aspect you can also use filters, interceptors for same thing. Here you can do it by:

a. create and set a threadlocal for per request bases. OR
b. add data to request attributes.

With aspects unfortunately its not possible ref: https://stackoverflow.com/a/72277110/1811348

  • Related