|
| 1 | +package cn.hncu.xmlImpl.aspectj; |
| 2 | + |
| 3 | +import org.aopalliance.aop.Advice; |
| 4 | +import org.aopalliance.intercept.MethodInterceptor; |
| 5 | +import org.aopalliance.intercept.MethodInvocation; |
| 6 | +import org.junit.Test; |
| 7 | +import org.springframework.aop.Advisor; |
| 8 | +import org.springframework.aop.aspectj.AspectJExpressionPointcut; |
| 9 | +import org.springframework.aop.framework.ProxyFactoryBean; |
| 10 | +import org.springframework.aop.support.DefaultPointcutAdvisor; |
| 11 | + |
| 12 | +public class AspectjDemo { |
| 13 | + |
| 14 | + @Test |
| 15 | + public void demo(){ |
| 16 | + |
| 17 | + ProxyFactoryBean factory = new ProxyFactoryBean(); |
| 18 | + factory.setTarget(new Person()); |
| 19 | + |
| 20 | + //声明一个aspectj切点 |
| 21 | + AspectJExpressionPointcut cut = new AspectJExpressionPointcut(); |
| 22 | + |
| 23 | + //设置需要拦截的方法-用切点语言来写 |
| 24 | + cut.setExpression("execution( int cn.hncu.xmlImpl.aspectj.Person.run() )");//拦截:空参返回值为int的run方法 |
| 25 | + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*() )");//拦截:空参空返回值的任意方法 |
| 26 | + //cut.setExpression("execution (void cn.hncu.xmlImpl.aspectj.Person.*(String))");//拦截:只有1个String类型参数,空返回值的任意方法 |
| 27 | + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(*) )");//拦截:有1个参数(类型不限),空返回值的任意方法 |
| 28 | + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(*,*) )");//拦截:有2个参数(类型不限),空返回值的任意方法 |
| 29 | + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(..) )");//拦截:任意(个数和类型)参数,空返回值的任意方法 |
| 30 | + //cut.setExpression("execution( int cn.hncu.xmlImpl.aspectj.Person.*(*,..) )");//拦截:至少有1个参数(类型不限),返回值类型是int的任意方法 |
| 31 | + //cut.setExpression("execution( * cn.hncu.xmlImpl.aspectj.Person.*(*,..) )");//拦截:至少有1个参数(类型不限),返回值类型任意的方法 |
| 32 | + //cut.setExpression("execution( * cn.hncu..*son.*(*,..) )");//拦截:cn.hncu包下,类名以"son"结束,至少有1个参数(类型不限),返回值类型任意的方法 |
| 33 | + |
| 34 | + Advice advice = new MethodInterceptor() { |
| 35 | + @Override |
| 36 | + public Object invoke(MethodInvocation invocation) throws Throwable { |
| 37 | + System.out.println("放行前拦截..."); |
| 38 | + Object obj = invocation.proceed();//放行 |
| 39 | + System.out.println("放行后拦截..."); |
| 40 | + return obj; |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + //切面=切点+通知 |
| 45 | + Advisor advisor = new DefaultPointcutAdvisor(cut,advice); |
| 46 | + factory.addAdvisor(advisor); |
| 47 | + Person p = (Person) factory.getObject(); |
| 48 | + |
| 49 | + p.run(); |
| 50 | + p.run(10); |
| 51 | + p.say(); |
| 52 | + p.sayHi("Jack"); |
| 53 | + p.say("Tom", 666); |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | +} |
0 commit comments