前言
本章讲解SpringAOP的基本概念以及它的一种实现方式Schema-based
方法
1.概念
依稀记得当初我第一次接触AOP的时候,基本上什么都不懂的!
AOP中文名称:面向切面编程
AOP英文名称:Aspect Oriented Programming
我们先来看下度娘给出的解释:
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
我们可能对上面的文字叙述有点看的不太懂,我这里给出一个例子:
我们正常执行程序的流程是自上而下的顺序,AOP的作用就是在某个方法执行的前后添加前置和后置通知,从而形成一个横向的切面,在方法执行之前先执行前置通知,方法执行之后执行后置通知的过程!
作用:减少冗余代码,比如我们需要对方法执行的前后记录日志,那么直接在方法上写显然会造成冗余,那么使用Spring的AOP技术将是一个不错的选择。
2.基于Schema-based实现AOP(用的不太多,但是需要掌握)
一、准备工作
1)需要引入对应的AOP的jar包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
2)基本概念
- 切点:原有的方法,即面向切面编程需要作用的方法
- 前置通知:在切点之前执行的功能
- 后置通知:在切点之后执行的功能
- 异常通知:如果在切点执行过程中发生异常,则执行异常通知
- 切面:以上所有统称切面
二、配置AOP
1)在Spring的配置文件中配置切点以及通知
<!-- 配置AOP -->
<!-- 配置前置和后置的通知bean -->
<bean id="before" class="cn.edu.ccut.advice.TestBeforeAdvice"></bean>
<bean id="after" class="cn.edu.ccut.advice.TestAfterAdvice"></bean>
<!-- 配置切面(切点、前置和后置通知) -->
<aop:config proxy-target-class="true">
<aop:pointcut id="myPoint" expression="execution(* cn.edu.ccut.service.impl.StudentServiceImpl.*(..))"></aop:pointcut>
<aop:advisor advice-ref="before" pointcut-ref="myPoint"></aop:advisor>
<aop:advisor advice-ref="after" pointcut-ref="myPoint"></aop:advisor>
</aop:config>
2)编写前置和后置通知的Java类
TestBeforeAdvice.java
package cn.edu.ccut.advice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class TestBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("我是前置通知!");
}
}
TestAfterAdvice.java
package cn.edu.ccut.advice;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class TestAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("我是后置通知!");
}
}
三、编写测试类测试
import cn.edu.ccut.bo.Student;
import cn.edu.ccut.service.IStudentService;
import cn.edu.ccut.service.impl.StudentServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class SpringTest {
@Test
public void testApplicationContext() throws Exception{
//加载spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取IStudentService
IStudentService studentService = ac.getBean("studentService", StudentServiceImpl.class);
List<Student> students = studentService.listAll();
System.out.println(students);
}
}
执行结果如下: