How to exclude methods from aspectj

2019-02-17 06:34发布

问题:

I'm trying to exclude several methods from log files using aspectj (Im usong spring and Load-time weaving). Is there a way to list the excluded methods in the aop.xml? I know i can do this for full classes but I'm looking for specific methods. or can i make a list in the aspect class? Thanks

回答1:

I don't know how to do it in an XML, but it's easy enough to do it in the aspects themselves, as pointcuts can be combined using boolean operators.

Traditional aspectj syntax:

pointcut whatIDontWantToMatch() : within(SomeClass+) || execution(* @SomeAnnotation *.*(..));
pointcut whatIWantToMatch()     : execution(* some.pattern.here.*(..));
pointcut allIWantToMatch()      : whatIWantToMatch() && ! whatIDontWantToMatch();

@AspectJ syntax:

@Pointcut("within(SomeClass+) || execution(* @SomeAnnotation *.*(..))")
public void whatIDontWantToMatch(){}
@Pointcut("execution(* some.pattern.here.*(..))")
public void whatIWantToMatch(){}
@Pointcut("whatIWantToMatch() && ! whatIDontWantToMatch()")
public void allIWantToMatch(){}

These are of course just samples. whatIDontWantToMatch() could also be composed of several pointcuts etc.



回答2:

Here is way for exclusion of method based on aop.xml or aop-ajc.xml in aspectj

<aspectj>
<aspects>
<aspect name="com.perf.aspects.EJBAspect"/>
    <concrete-aspect name="com.perf.aspects.ConcreteAspectEJBInclude" extends="com.perf.aspects.EJBAspect">
    <pointcut name="ejbPointCutInclude"
        expression="execution(* com.perf.test.TestClass..*(..))" /> 
       <!-- Methods to exclude for the above execution methods in TestClass. This will also exclude all calls below excluded method -->
     <pointcut name="ejbPointCutExclude"
        expression="(execution(* com.perf.test.TestClass.getName(..))) || (execution(* com.perf.test.TestClass.getCity(..))) || cflow(execution(* com.perf.test.TestClass.getCity(..))) || cflow(execution(* com.perf.test.TestClass.getName(..))) " /> 
    </concrete-aspect>               
</aspects>
</aspectj>

Create below abstract aspect

public abstract  aspect EJBAspect 
{

    public pointcut ejbPointCutInclude();
    public pointcut ejbPointCutExclude(): ;     


    before() : ejbPointCutInclude() &&  !ejbPointCutExclude() 
    {               
        doBefore(thisJoinPointStaticPart.getSignature());       
    }

    after() :  ejbPointCutInclude() && !ejbPointCutExclude() 
    {               
        doAfter(thisJoinPointStaticPart.getSignature());
    }
}