vendredi 29 juillet 2016

AspectJ runtime weaver

I'm studying AspectJ and i want to test my lib aspect. I want to weave target class with my aspect programmatically. For instance, i want to create abstract aspect with before advice which will throw exception if argument equals to "Bob".

NotBobAspect.aj

package mezlogo;

public abstract aspect NotBobAspect {
    abstract pointcut boblessZone();

    before(String name): boblessZone() && args(name) {
        if ("bob".equalsIgnoreCase(name)) {
            throw new PleaseNotBobException();
        }
    }
}

Is it possible to test within one test? I talk about some runtime class loader.

Like BoblessServiceTest.java:

package mezlogo;

import org.aspectj.weaver.loadtime.WeavingURLClassLoader;
import org.junit.Test;

import java.net.URL;

public class BoblessGreetingTest {
    @Test(expected = PleaseNotBobException.class)
    public void should_throw_BOB_EXCEPTION_when_weaved_in_runtime_service_retrive_BOB() throws Exception {
        ClassLoader classLoader = Greeting.class.getClassLoader();

        URL AOP_XML = classLoader.getResource("META-INF/aop.xml");
        URL aspect = classLoader.getResource("mezlogo/NotBobAspect.class");
        URL clazz = classLoader.getResource("mezlogo/Greeting.class");

        WeavingURLClassLoader weavingLoader = new WeavingURLClassLoader(
                new URL[]{clazz}, 
                new URL[]{aspect, AOP_XML}, 
                classLoader);

        Class<Greeting> serviceClass = (Class<Greeting>) weavingLoader.loadClass("mezlogo.Greeting");
        Greeting greeting = serviceClass.newInstance();
        greeting.hello("Bob");
    }
}

aop.xml

<aspectj>
    <aspects>
        <concrete-aspect name="mezlogo.BoblessService" extends="mezlogo.NotBobAspect">
            <pointcut name="boblessZone" expression="execution(* mezlogo.*.*(String))"/>
        </concrete-aspect>
    </aspects>
</aspectj>

Greeting.java

package mezlogo;

public class Greeting {
    public String hello(String name) { return "Hello, " + name; }
}

My first steps was: AspectJ - Weaving with custom ClassLoader at runtime and Runtime weaving without agent but I did not understand how to reload/redefine concrete class with concrete aspect and definition (aop.xml).

Aucun commentaire:

Enregistrer un commentaire