更多请看 http://blog.youkuaiyun.com/wangpeng047/article/details/8560694
在上篇博文中,我向大家介绍了Aop重要概念和教程,这回给出代码示例。
一、XML方式
1. TestAspect:切面类
- package com.spring.aop;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- public class TestAspect {
- public void doAfter(JoinPoint jp) {
- System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
- }
- public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
- long time = System.currentTimeMillis();
- Object retVal = pjp.proceed();
- time = System.currentTimeMillis() - time;
- System.out.println("process time: " + time + " ms");
- return retVal;
- }
- public void doBefore(JoinPoint jp) {
- System.out.println("log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
- }
- public void doThrowing(JoinPoint jp, Throwable ex) {
- System.out.println("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception");
- System.out.println(ex.getMessage());
- }
- }
2. AServiceImpl:目标对象
- package com.spring.service;
- // 使用jdk动态代理
- public class AServiceImpl implements AService {
- public void barA() {
- System.out.println("AServiceImpl.barA()");
- }
- public void fooA(String _msg) {
- System.out.println("AServiceImpl.fooA(msg:" + _msg + ")");
- }
- }
3. BServiceImpl:目标对象
- package com.spring.service;
- // 使用cglib
- public class BServiceImpl {
- public void barB(String _msg, int _type) {
- System.out.println("BServiceImpl.barB(msg:" + _msg + " type:" + _type + ")");
- if (_type == 1)
- throw new IllegalArgumentException("测试异常");
- }
- public void fooB() {
- System.out.println("BServiceImpl.fooB()");
- }
-
-
-