*
切点语言:
* 1) 框架: execution( 切点语言表达式 )
* 2) 表达式格式: 返回类型 包名.[子包名.]类名.方法名(参数类型列表)
* 3) "."号是包名之间 或 包名与类名之间 或 类名与方法名 之间的间隔符
* 4) ".."在包路径位置代表的是任意深的目录,在参数类型列表中代表的是任意个数与类型的参数
* 5) "*"号 是操作系统中的通配符**
一个被代理拦截的类:
public class Person {
public void run(){
System.out.println("running......");
}
public void hello(){
System.out.println("hello......");
}
public void fun(String str){
System.out.println(str);
}
public String abc(String str){
System.out.println(str);
return str+"OK";
}
public String ok(String str, int i){
System.out.println(str+i);
return str+i;
}
}
public class AspectjDemo {
@Test
// 切面=切点+通知
public void t1() {
// 1代理工厂及代理原型
ProxyFactoryBean factory = new ProxyFactoryBean();
factory.setTarget(new Person());
// 2声明切点-----版本2的标志,就是切点采用aspectj
AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
// 设置切点的表达式---切点语言
cut.setExpression("execution( void cn.hncu.v2.Person.run() )"); // 写死的
// 3通知
Advice advice = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("前面拦3.....");
Object res = invocation.proceed();// 放行
System.out.println("后面拦3.....");
return res;
}
};
// 4切面=切点+通知
Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
// 5把切面加到代理工厂
factory.addAdvisor(advisor);
// //////从代理工厂中取出的bean都是被代理过的
Person p = (Person) factory.getObject();
p.run();
p.hello();
}
@Test
// 演示节点语言
public void t2() {
ProxyFactoryBean factory = new ProxyFactoryBean();
factory.setTarget(new Person());
// 2声明切点-----版本2的标志,就是切点采用aspectj
AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
// 设置切点的表达式---切点语言
//cut.setExpression("execution( void cn.hncu.v2.Person.*() )"); // 拦Person中的: 所有返回类型为空的空参方法
//cut.setExpression("execution( void cn.hncu.v2.Person.*(String) )"); // 拦Person中的: 所有返回类型为空的,参数为一个String的方法
//cut.setExpression("execution( void cn.hncu.v2.Person.*(*) )"); // 拦Person中的: 所有返回类型为空的,有且仅有一个参数的方法
//cut.setExpression("execution( * cn.hncu.v2.Person.*(*) )"); // 拦Person中的: 所有返回类型为任意,有且仅有一个参数的方法
//cut.setExpression("execution( String cn.hncu.v2.Person.*(..) )"); // 拦Person中的: 所有返回类型为String,参数任意个数,任意类型
//cut.setExpression("execution( * cn.hncu..*son.*(..) )"); // 拦Person中的: 返回类型为任意,cn.hncu包下的任意子目录,类名以son结尾,方法名任意,参数任意(类型和个数)
cut.setExpression("execution( * cn.hncu..*son.*(*,..) )"); // 拦Person中的: 返回类型为任意,cn.hncu包下的任意子目录,类名以son结尾,方法名任意,参数至少一个
Advice advice = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("前面拦3.....");
Object res = invocation.proceed();// 放行
System.out.println("后面拦3.....");
return res;
}
};
Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
factory.addAdvisors(advisor);
Person p = (Person) factory.getObject();
p.run();
p.hello();
p.fun("aaabbccc111");
p.abc("abc123");
p.ok("hncu", 66);
}
}