aop的认识
aop又叫面向切面编程,在原有纵向执行流程中添加横切面,不需要修改原有程序代码(体现出程序的高扩展性)
原有功能相当于释放了部分逻辑,让职责更加明确
面向切面编程是什么?
在程序原有纵向执行流程中,针对某一个或某一些方法添加通知,形成横切面的过程就叫做面向切面编程
常用的一些概念
-
原有功能:切点,pointcut
-
前置通知:在切点之前执行的功能,before advice
-
后置通知:在切点之后执行的功能,after advice
-
如果切点执行过程中出现异常,会触发异常通知,throws advice
-
所有功能总称叫做切面
-
织入:把切面嵌入到原有功能的过程叫做织入
-
spring提供了两种aop实现方式
-
第一种方式:Schema-based 每个通知都需要实现接口或者类
-
配置spring配置文件是在<aop:config>配置
-
第二种方式:AspectJ 每个通知不需要实现接口或者类
-
配置spring配置文件是在<aop:config>的子标签<aop:aspect>中配置
aop的配置文件
<?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 id="mybefore" class="com.ning.advice.MyBeforeAdvice"/>
<bean id="myafter" class="com.ning.advice.MyAfterAdvice"/>
<!--配置切面-->
<aop:config>
<!--配置切点-->
<aop:pointcut id="mypoint" expression="execution(* com.ning.test.Demo.demo2())"/>
<aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/>
<!--通知-->
<aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/>
</aop:config>
<!--配置Demo类,测试时使用-->
<bean id="demo" class="com.ning.test.Demo"/>
</beans>
需要实现两个接口
package com.ning.advice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class MyAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行后置通知");
}
}
package com.ning.advice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class MyBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("执行前置通知");
}
}
测试类
public class Demo {
public void demo1(){
System.out.println("demo1");
}
public void demo2(){
System.out.println("demo2");
}
public void demo3(){
System.out.println("demo3");
}
}
package com.ning.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// Demo demo = new Demo();
// demo.demo1();
// demo.demo2();
// demo.demo3();
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo", Demo.class);
demo.demo1();
demo.demo2();
demo.demo3();
}
}