【问题标题】:Pointcut not working with Spring AOP切入点不适用于 Spring AOP
【发布时间】:2010-10-02 02:57:49
【问题描述】:

为了使用 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!!

【问题讨论】:

    标签: java spring logging aop spring-aop


    【解决方案1】:

    我只是在检查您的代码,但我有一种预感,问题是您没有从 Spring 获取您的 TixServiceImpl 实例,而是您自己在 TixClient 中手动实例化它。我认为您的 TixService 需要是一个 Spring bean,从 Spring ApplicationContext 获取,以便 Spring 有机会在返回的实例上设置方面。

    【讨论】:

    • 感谢您的提示,它成功了。如果在线提供的示例/示例/教程中提到了这一点,那就太好了。
    【解决方案2】:

    Scott Bale 是对的:让 spring 为您实例化 TixServiceImpl。同样在这种情况下,启用 Springs 日志记录可能会有所帮助,因为它会告诉您找到了多少方面/服务的目标。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多