面向切面编程的感觉就是:以前程序是由上往下执行的,如果我需要添加一个什么功能,就需要去改代码,但是我用AOP的动态代理,就像胶带一样,往上面一贴就行了,不要用的时候再撕下来,是横向的,后面会有很多胶带的类型(就是下面的Advice通知),往上贴,往下帖,环绕贴,遇到异常贴等等,就很方便
1、AOP相关术语:
2、AOP的配置和简单测试:
这里先用xml配置的方式,后面再说注解的方法
- 导包 :Spring_AOP开发jar包
- 配置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"
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"> <!-- bean definitions here -->
<!-- 需要被代理的对象 -->
<bean id="AopDemo" class="cn.nupt.aopDemo.AopDemo"></bean>
<!-- 切面类 -->
<bean id="AopInsert" class="cn.nupt.aopClass.AopInsert"></bean>
<aop:config>
<!-- 配置哪些类的哪些方法需要进行增强,这里是AopDemo下面的hehe方法 -->
<aop:pointcut expression="execution(* cn.nupt.aopDemo.AopDemo.hehe(..))" id="hehe" />
<!-- 配置切面 -->
<aop:aspect ref="AopInsert">
<!-- 在hehe方法前面设置我们切面类的check方法 -->
<aop:before method="check" pointcut-ref="hehe" />
</aop:aspect>
</aop:config>
</beans>
- 编写运行类(就是要被代理/增强的类)
package cn.nupt.aopDemo;
public class AopDemo {
public void haha() {
System.out.println("haha");
}
public void hehe() {
System.out.println("hehe");
}
public void xixi() {
System.out.println("xixi");
}
}
- 编写切面类
package cn.nupt.aopClass;
//编写切面类
public class AopInsert {
public void check() {
System.out.println("权限校验中。。。");
}
}
- 编写测试类,这里用到了junit和AOP的整合
package cn.nupt.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.nupt.aopDemo.AopDemo;
//junit和aop整合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Resource(name="AopDemo")
private AopDemo aopDemo;
@Test
public void test() {
aopDemo.haha();//输出haha
aopDemo.hehe();//输出hehe
aopDemo.xixi();//输出xixi
}
}
输出:
haha
权限校验中。。。
hehe
xixi