为Spring PetClinic添加新的方面

时间:2011-12-09 18:05:10

标签: java spring aop aspectj

尝试在org.springframework.samples.petclinic中的方面包中添加新的方面类。

我的方面类如下:

package org.springframework.samples.petclinic.aspects;

import org.apache.openjpa.jdbc.sql.Join;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.samples.petclinic.context.SessionContext;

import java.util.Date;

@Aspect
public class MethodLogAspect {

    Logger logger = LoggerFactory.getLogger(MethodLogAspect.class);

    @Pointcut("execution(* org.springframework.samples..*.*(..))")
    public void methodLogging(){}

    @Before("methodLogging()")
    public void logMethodStart(JoinPoint joinPoint){

        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();
        logger.info("class name: "+className+"invoked method:"+methodName+" at "+ ((new Date()).getTime()));
    }

    @After("methodLogging()")
    public void logMethodEnd(JoinPoint joinPoint){
                String methodName = joinPoint.getSignature().getName();
                String className = joinPoint.getTarget().getClass().getName();
                logger.info("class name: "+className+"finished invoking method:"+methodName+" at "+ ((new Date()).getTime()));
    }

}

然后我继续在/ resources / META-INF的aop.xml中进行如下操作:

<?xml version="1.0"?>

<!-- Custom aspects for the PetClinic sample application -->
<aspectj>

    <weaver>
        <include within="org.springframework.samples.petclinic..*"/>
    </weaver>

    <aspects>
        <aspect name="org.springframework.samples.petclinic.aspects.UsageLogAspect"/>
        <aspect name="org.org.springframework.samples.petclinic.aspects.MethodLogAspect"></aspect>
        <concrete-aspect name="org.springframework.samples.petclinic.aspects.ApplicationTraceAspect"
                extends="org.springframework.samples.petclinic.aspects.AbstractTraceAspect">
            <pointcut name="traced" expression="execution(* org.springframework.samples..*.*(..))"/>
        </concrete-aspect>
    </aspects>

</aspectj>

当我构建战争并部署它时,我的方面中指定的输出都不会显示在日志中。我不确定我在这里错过了哪一步。我也觉得我不理解一切如何捆绑在一起的机制。有人可以指出我所缺少的东西并给我一个正确方向的推动。

由于

编辑:

我能够通过将bean(aspect)添加到webapp / WEB-INF / spring文件夹中的applicationContext-jdbc.xml来解决此问题。我不确定为什么这会起作用?有人能给我一个解释吗? -Thanks

1 个答案:

答案 0 :(得分:2)

我不确定Aspectj编织配置,但在Spring AOP中你可以使用

<aop:aspectj-autoproxy/> 

启用@Aspect注释的自动检测。阅读http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-ataspectj了解更多信息