Search code examples
javaspringspring-bootannotationsaop

Create basic Java lib to change the method return using annotion


How can I create a basic lib with AOP concepts? I'd like to create a lib with some annotations and aspects and configure it as a dependency in other projects.

Is there a non-intrusive way to do this? I would not like to configure the main project with @EnableAspectJAutoProxy or insert other dependencies.

Thanks


Solution

  • I think basically there are two different questions in this one:

    1. How to create a reusable library in spring boot
    2. How to do the aspects related stuff

    Part 1

    To answer the first part of the question, I suggest reading about spring factories. This mechanism basically allows to define an auto-configuration, so that when you'll import the module with spring factories spring boot application of the customer will automatically detect your beans and will load them into the application context.

    Once you grasp the concept, you'll find out that different spring boot projects have different component scanning policies, so you really want to rely on the component scanning, hence you'll create a Java Config where you'll register all your beans.

    This java config (@Configuration annotated class) will be specified in spring.factories - a small overhead that IMO definitely pays off in this case.

    Regarding the API of this module, probably the best way is to define some annotations of runtime retention policy) so that the users of the module will use them in their code. They'll have these annotations since they are supposed to add your module as a dependency to their code.

    The last point here is: the module of the library should be a regular JAR not a spring boot application or something, so you don't need to use a spring-boot-maven-plugin here

    Part 2

    Now as for the second part. Yes, AOP can work for you here, however this would require the applications to introduce the whole AOP framework. While its possible, I would argue that its not the ideal way: many won't really like this approach stating that its too intrusive.

    In spring paralance, there is a concept of BeanPostProcessors. That probably will be a better choice in this case. Essentially you can achieve similar results as Spring AOP but without really introducing an AOP.

    There is a lot of material about bean post processors, to give you an idea, these are regular beans (that's why I've talked about the java configuration of the beans) that spring treats differently:

    Once loaded they can be applied to all other beans and among other things they can wrap a beans that seem to be relevant (read annotated with annotations exposed by the module API) in proxy generated on-the-fly. This proxy can alter the behavior of the annotated method, change the result, cache the result, eavesdrop the call, do whatever you want to do).