Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a JAR with an aspect that is automatically applied to classes in client project?

I want to have a JAR with an aspect that intercepts all method calls, e.g.

@Aspect
public class CoolAspect {
    @Pointcut("execution(public * *(..))")
    public void anyPublicMethod() { }

    @Before("anyPublicMethod()")
    public void advice(JoinPoint point) {
       System.out.println("sign:\t" + point.getSignature());
    }
}

Suppose the above is the aspect I have and want clients to use. I compile it to a JAR and make available to Maven.

Now the clients would use this jar as a dependency, e.g.

    <dependency>
        <groupId>cool-group</groupId>
        <artifactId>cool-artifact</artifactId>
        <version>1.0.0</version>
    </dependency>

This artifact (JAR) has the mentioned aspect.

Now is it possible for the aspect work by just declaring a Maven dependency?

Few things that might be important:

  1. I plan to use AspectJ (perhaps Spring AOP, if necessary),
  2. The clients will probably be web applications with normal web.xml etc.
  3. Clients are built with Maven
  4. I want the Clients to be as easy to configure as possible - in my original idea a Maven dependency would be enough.
  5. The "Annotation JAR" will contain a web-fragment, so it's possible to declare some custom ServletContextListener there..

Any ideas?

like image 370
Parobay Avatar asked Dec 19 '13 11:12

Parobay


1 Answers

Find a simple solustion for this question if you are using spring-boot:

In the jar, you can define your aspect as a component:

package com.xxx.yy.zz.aspect;
@Aspect
@Component
public class CoolAspect {
   // code like the question
}

And the, you need create a file spring.factories in /resources/META-INF/. Spring will scan this file when start.

And the file spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xxx.yy.zz.aspect.CoolAspect

After that, just package them as a jar.

This will work by just declaring a Maven dependency

like image 142
Chao Jiang Avatar answered Sep 23 '22 05:09

Chao Jiang