春天& AspectJ记录器

时间:2014-11-06 21:49:12

标签: java spring logging annotations aspectj

我正在尝试使用注释记录创建一个小型弹簧项目。

首先,我添加了Spring AOP xsdnamespace

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

并添加了AOP aspectj proxy

<aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true" />

添加了注释界面:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Loggable {
   String message() default " -- ";
}

之后我创建了Aspect类:

@Aspect
public class LogManager {

    @Before("execution(* spring.TestServlet.processRequest(..))")
    public void logBefore(JoinPoint joinPoint) {

        System.out.println("logBefore() is running!");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("******");
    }

    @Pointcut("execution(public * *(..))")
    public void publicMethod() {
        System.out.println("Pointcut success");
    }

    @Around("publicMethod() && @annotation(spring.aspects.annotations.Loggable)")
    public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Log logger = getLog(joinPoint.getTarget().getClass());
        StopWatch sw = new StopWatch();
        Object[] args = joinPoint.getArgs();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = className + ": " + joinPoint.getSignature().getName();
        String argString = "";

        logger.error(methodName + " Started");
        logger.error("Params: ");

        for (Object arg : args) {
            logger.error("    " + arg.getClass().getName() + ": " + arg);
        }

        sw.start();
        joinPoint.proceed();
        sw.stop();

        System.out.println(methodName + "finished execution in " + sw.prettyPrint());
        logger.error(methodName + " finished execution in " + sw.prettyPrint());
    }
}

在此设置之后,我将注释添加到我的方法中但没有发生任何事情。

我在Tomcat Server 8.0.1 JDK 1.7 Java EE 7 Web上运行此代码 提前感谢您的帮助,
马蒂亚

0 个答案:

没有答案