Pergunta

I'm trying to use Spring to provide load time weaving to several classes in a project I've created. I'm having trouble getting it to work when I call a class that is not within my local project.

I created a class named ExampleClass and when I perform an @Around on a method in there, I can see the modifications I made to the return, however when I attempt to do the same to String I'm unable to get any results.

This is my Aspect Code:

@Pointcut("call(* java.lang.String.*(..))")
public void cutString() {}

@Before("cutString()")
public void aroundString() throws Throwable {
    System.out.println("I Never See This");
}

Here's my call to that code:

public class Main {
    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("classpath:my-context.xml");

        String string = new String("I Only See This");
        System.out.println(string.toLowerCase());
    }
}

The content of my-context.xml is just a <context:load-time-weaver />.

I have an aop.xml defined which as I said works for one class, but not another:

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
    <weaver>
        <include within="com.example.*" />
        <include within="java.lang.String" />
    </weaver>

    <aspects>
        <aspect name="com.example.PerformMonitor" />
    </aspects>
</aspectj>

Am I missing something, or is this a limitation of Spring and AspectJ?

Foi útil?

Solução

Per default aspectj will not weave any java standard classes. This is a limitation to prevent security leaks as far as i remember. It is described in the aspectj documentation. Probably there is a property which allows changing this behavior but you should be very sure you need this before you start doing that.

Just create another jar with one class of your own and try to weave this one. This should work out of the box.

Outras dicas

Martin Frey is right. There are ways to weave JDK classes (I have done it), but it is a bit tricky and not for newbies - and mostly not necessary. Your alternative is to intercept the calls to, not the execution of your external methods. This way you do not need to weave into them. Clean and easy. Just use call() instead execution() for your external classes.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top