0

I am using spring aop to create an annotation for some crosscut purpose. Below is the sample:

@Aspect
@Component
@Slf4j
public class MyAspect {
    @Autowired
    private MyService myService

    @Before("@annotation(MyAnnotationCheck)")
    @SneakyThrows
    public void check(JoinPoint joinPoint) {
        // This is the object that I am going to reload in the
        // function that being marked by the annotation I created.
        // Anyway I can pass this into the annotated method instead
        // of load from db again?
        EntityA myObj = myService.loadFromDB();
        // ...
    }
}

Following is the method being annotated, which is in different class

@MyAnnotationCheck(checkType = "abc")
public void myMethod(MyRequest request) {
    EntityA objA = myService.loadFromDB();  // Reload the object from DB
}

What should I do with it? Anyway I can pass the object from the Aspect function to the method annotated?

kriegaex
  • 63,017
  • 15
  • 111
  • 202
Laodao
  • 1,547
  • 3
  • 17
  • 39
  • Why not use `joinPoint.proceed()`? – Unmitigated Jan 18 '23 at 17:05
  • @Unmitigated, how to do that? Could you please give me an example? Thanks. – Laodao Jan 18 '23 at 17:38
  • I do not think it is possible to do unless you create a new field in `MyRequest` class say EntityA and set that field in the aspect(ater getting hold of myRequest Object in Aspect through `joinPoint.getArgs()`. And you can access that in myMethod. You can define this new field as `@Transient` Another option is you can use a cache for this call `myService.loadFromDB()` so that it is not reloaded from DB. – pvpkiran Jan 18 '23 at 20:16

1 Answers1

0

You cannot use aspects to magically inject objects into local variables. The term "local" says it all, does it not? If you use Spring, you should be familiar with a concept called dependency injection. Just use that concept. Instead of creating dependencies by yourself in the method where you need it, make sure that it can be injected from outside. But in this case, it is maybe easier to configure DB caching according to your needs.

The main problem with your question is your pseudo code and that neither you nor the code explain the problem you are actually trying to solve. For example, what is MyRequest request used for? How does myService.loadFromDB() know what exactly to load from the DB. Nobody can help you adequately, if you post code which does not resemble reality.

kriegaex
  • 63,017
  • 15
  • 111
  • 202