本篇博客知识点:
SpringAOP第二种技术学习— AspectJ
AspectJ:与上篇博客中讲的第一种技术的区别在于他的切点,即利用他的切点语言拦截多种类型的函数,类的。
举个例子:以前我们仅仅能拦截 类判断是不是Person类,再来拦截,Asperctj可以根据你的类名,包名,函数名,参数名,返回类型等来拦截。
具体实例
先看所需要的包
纯Java代码方式—
需要的Person.java
package cn.hncu2.v2;
/**
* @author<a href="mailto:953801304@qq.com">胡龙华</a>
*/
public class Person {
public void run(){
System.out.println("I'm running!");
}
public void Hello(){
System.out.println("Hello,Spring!");
}
}
实际代码
public class Demo2 {
/*
* 切点语言:
* 1) 框架: execution( 切点语言表达式 )
* 2) 表达式格式: 返回类型 包名.[子包名.]类名.方法名(参数类型列表)
* 3) "."号是包名之间 或 包名与类名之间 或 类名与方法名 之间的间隔符
* 4) ".."在包路径位置代表的是任意深的目录,在参数类型列表中代表的是任意个数与类型的参数
* 5) "*"号 是操作系统中的通配符
*/
@Test
public void test1(){
Person p = new Person();
ProxyFactoryBean factory = new ProxyFactoryBean();
factory.setTarget(p);
AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
cut.setExpression("execution( void cn.hncu2.v2.Person.run() )");
// 设置切点的表达式---切点语言
// cut.setExpression("execution( void cn.hncu.v2.Person.run() )"); // 写死的
Advice advice = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("---------");
Object obj = invocation.proceed();
System.out.println("---------");
return obj;
}
};
Advisor advisor = new DefaultPointcutAdvisor(cut,advice);
factory.addAdvisor(advisor);
Person p2 = (Person) factory.getObject();
p2.run();
p2.Hello();
}
}
Spring的XML方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 自动代理 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
<bean id="advisor" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
<property name="expression" value="execution(void cn.hncu2.v2.Person.run() )"/>
<property name="advice">
<bean class="cn.hncu2.v2.AroundAdvice"></bean>
</property>
</bean>
<bean id="p" class="cn.hncu2.v2.Person"></bean>
</beans>
测试代码以及结果,只拦截了run方法