https://www.cnblogs.com/duanxz/p/5194801.html
<!-- 启动AspectJ自动代理 -->
<aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true"/>
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。proxy-target-class=”false” false 是以jdk实现动态代理 true 是以CGLib实现动态代理(这时需要cglib库)
@Component
@Aspect
public class TimerAop {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("execution(* com.tujia.tns.advert.dao..*.*(..))")
private void pointcut() {
}
@Around(value = "pointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
long start = System.currentTimeMillis();
Object proceed;
try {
proceed = joinPoint.proceed();
} catch (Throwable t) {
logger.error("error while record execute time", t);
throw new RuntimeException(t);
}
Signature signature = joinPoint.getSignature();
String key = String.format("time_log_%s_%s", signature.getDeclaringType().getSimpleName(), signature.getName());
TMonitor.recordOne(key, System.currentTimeMillis() - start);
//todo del
logger.info("record execute time, key:{}, cost:{}", key, System.currentTimeMillis() - start);
return proceed;
}
}
在controller中使用AOP
在controller中使用AOP的问题主要在于如何让controller能够被检测到。
controller和其他spring bean的区别在于:controller是由mvc定义并在web.xml中的dispatcher中定义的。
解决方法:
1、正确定义controller,(比较通用的做法,没有特殊情况的话,大部分应用没有这个问题)
a. 将服务层的类都放在ApplicationCotext-.xml中定义,在context listener中初始化(注意,任何controller都不应该在这里出现),要包括
b. 定义mvc的配置文件,一般是 <
c. 另外一个事项,controller需要使用@controller注释,而不是继承abstract controller。
d. 建议使用aspectj来完成aop
注意:引入 xmlns:aop="http://www.springframework.org/schema/aop"
, xsi[http://www.springframework.org/schema/aop](http://www.springframework.org/schema/aop) [http://www.springframework.org/schema/aop/spring-aop.xsd](http://www.springframework.org/schema/aop/spring-aop.xsd)