Spring AOP的周围建议和@annotation不工作 [英] Spring AOP with Around advice and @annotation not working

查看:969
本文介绍了Spring AOP的周围建议和@annotation不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring AOP在我的应用程序日志记录。这里是applicationContext.xml文件

I am using Spring AOP for logging in my application. Here is the applicationContext.xml file

<mvc:annotation-driven />
<context:component-scan base-package="com.template" />
<context:annotation-config />
<jpa:repositories base-package="com.template.repository"/>
<tx:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/template?autoReconnect=true"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
    <property name="persistenceUnitName" value="template"/>

</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

和我aopLogging.xml是

and my aopLogging.xml is

<bean id="aopLogging" class="com.template.log.AopLoggingAspect" />
<aop:aspectj-autoproxy proxy-target-class="false"/>

和我看点类

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
public class AopLoggingAspect {

private static final Logger logger = Logger.getLogger(AopLoggingAspect.class);

@Around(value="@annotation(com.template.log.Loggable)")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable{
        Object retVal = null;
        try {
            StringBuffer startMessageStringBuffer = new StringBuffer();

            startMessageStringBuffer.append("Start method execution :: ");
            startMessageStringBuffer.append(joinPoint.getSignature().getName());
            startMessageStringBuffer.append("(");

            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                startMessageStringBuffer.append(args[i]).append(",");
            }
            if (args.length > 0) {
                       startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1);
            }

            startMessageStringBuffer.append(")");
            logger.info(startMessageStringBuffer.toString());
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            retVal = joinPoint.proceed();
            stopWatch.stop();

            StringBuffer endMessageStringBuffer = new StringBuffer();
            endMessageStringBuffer.append("Finish method ");
            endMessageStringBuffer.append(joinPoint.getSignature().getName());
            endMessageStringBuffer.append("(..); execution time: ");
            endMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
            endMessageStringBuffer.append(" ms;");

            logger.info(endMessageStringBuffer.toString());
        } catch(Exception ex) {
            StringBuffer errorMessageStringBuffer = new StringBuffer();
            logger.error(errorMessageStringBuffer.toString(), ex);
            throw ex;
        }
        return retVal;
}
}

和我的自定义注释是

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Loggable {
}

和我的服务类

public class UserService {
@Transactional(readOnly=true)
@Loggable
public User getUserByUserId(Long userId){
return userRepository.findOne(userId);
}
}

的问题是,没有得到打印日志。请帮帮我。提前致谢。请不要让我知道是否需要任何其他信息。

The problem is that the logs are not getting printed. Please help me. Thanks in advance. Please do let me know if any other info is needed.

推荐答案

这不是你问什么,但它可能是有用的。我实现了一个增强的AOP记录器。它有你需要的功能和许多其他功能。请参见 https://github.com/nickvl/aop-logging

It is not exactly what you have asked, but it could be useful. I implemented an enhanced aop logger. It has functionality you need and lots of additional features. See https://github.com/nickvl/aop-logging

PS
根据春季版和整个应用程序上下文是否值得尝试在aopLogging.xml接通代理的类​​:

PS depending on spring version and the whole application context it worth to try switching on proxy for classes in your aopLogging.xml:

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

这篇关于Spring AOP的周围建议和@annotation不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆