切入点不适用于Spring AOP

时间:2009-01-18 18:31:52

标签: java spring logging aop spring-aop

为了使用Spring AOP实现Logging,我遵循了这些简单的步骤。但它似乎无法正常工作。任何帮助都是有用的

1)创建 MyLoggingAspect

    import org.aspectj.lang.ProceedingJoinPoint;

public class MyLoggingAspect
{

    public MyLoggingAspect() {
        super();
        System.out.println("Instantiated MyLoggingAspect");     
    }

    public Object log(ProceedingJoinPoint call) throws Throwable
    {
        System.out.println("from logging aspect: entering method [" + call.toShortString()
                            +"] with param:"+call.getArgs()[0] );

        Object point =  call.proceed();

        System.out.println("from logging aspect: exiting method [" + call.toShortString()   
                            + "with return as:" +point);        

        return point;
    }

}

2)创建了一个我希望记录的类( TixServiceImpl

public class TixServiceImpl implements TixService{

    @Override
    public void calculateSomething() {
        String s = "did some calculation..";
        System.out.println(s);
    }

    @Override
    public String getTixName() {
        return null;
    }
}

3)创建了 spring-aspectj.xml 文件

<beans...    
    <bean id="LoggingAspect"  class = "MyLoggingAspect"/>
    <aop:config>
          <aop:aspect ref="LoggingAspect">
             <aop:pointcut id="myCutLogging"
                    expression="execution(* TixService*.*(..))"/>
             <aop:around pointcut-ref="myCutLogging" method="log"/>
          </aop:aspect>
    </aop:config>    
</beans>

4)创建了一个简单的测试客户端( TixClient

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TixClient {

    public static void main(String[] a){

        ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring-aspectj.xml");

        TixService tix = new TixServiceImpl();
        tix.calculateSomething();
        String s = tix.getTixName();

        System.out.println("End of the the client invocation!!"); 
    }   
}

5)它给了我以下输出

...
Instantiated MyLoggingAspect
did some calculation..
End of the the client invocation!!

2 个答案:

答案 0 :(得分:15)

我只是检查你的代码,但是我预感到问题是你没有从Spring获得TixServiceImpl实例,而是你自己在{{1}中自己实例化它}。我认为你的TixClient需要是一个Spring bean,来自Spring ApplicationContext,所以Spring有机会在返回的实例上设置方面。

答案 1 :(得分:2)

Scott Bale是对的:让Spring为您设置TixServiceImpl。同样在这种情况下,启用Springs记录可能会有所帮助,因为它会告诉您已找到方面/服务的目标数量。