AOP面向切面编程定义
AOP全称Aspect Oriented Progremming,意为面向切面编程,利用AOP对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP的作用及优势
作用:在程序运行期间,不修改源代码对已有方法进行增强。
优势:
- 减少重复代码
- 减少重复代码
- 提高开发效率
- 维护方便
AOP相关专业术语(了解)
Joinpoint(连接点) | 在业务层service方法中连接业务和增强方法(代理)的方法 |
Pointcut(切入点) | 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义 |
Advice(通知/增强) | 拦截到Joinpoint之后所要做的事情就是通知 |
Introduction(引介) | 引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或Field |
Weaving(织入) | 指把增强应用到目标对象来创建的代理对象的过程 |
Proxy(代理) | 一个类被AOP织入增强后,就产生一个结果代理类 |
基于注解模拟日志信息
1.在pom.xml中引入jar包坐标依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-aop-xml</artifactId>
<groupId>xjit</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-aop-zj</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<!-- 解析aop切入表达式 * service.impl.*.*(..) -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
</dependencies>
</project>
2.创建service接口及实现类
package service;
public interface IAccountService {
void updateAccount(int i);
void saveAccount();
int deleteAccount();
}
package service.impl;
import org.springframework.stereotype.Service;
import service.IAccountService;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Override
public void updateAccount(int i) {
System.out.println("更新了!");
}
@Override
public void saveAccount() {
System.out.println("保存了!");
}
@Override
public int deleteAccount() {
System.out.println("删除了!");
return 0;
}
}
3.创建日志工具类
package utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 用于记录日志的工具类
*/
@Component("/logger")
@Aspect//表示当前类为切面类
public class Logger {
@Pointcut("execution(* service.impl.*.*(..))")
private void pt1(){}
@Before("pt1()")
public void beforePrintLog(){
System.out.println("Logger中的beforePrintLog方法开始记录前置通知日志");
}
@AfterReturning("pt1()")
public void afterPrintLog(){
System.out.println("Logger中的afterPrintLog方法开始记录后置通知日志");
}
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("Logger中的afterThrowingPrintLog方法开始记录异常通知日志");
}
@After("pt1()")
public void lastPrintLog(){
System.out.println("Logger中的lastPrintLog方法开始记录最后通知日志");
}
}
4.在资源文件路径下创建配置文件bean.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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="service"/>
<context:component-scan base-package="utils"/>
<!-- 配置spring开启注释aop的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
5.创建测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountService;
import service.impl.AccountServiceImpl;
public class AOPTest {
public static void main(String[] args) {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取对象
IAccountService as = (IAccountService) ac.getBean("accountService");
//执行方法
as.saveAccount();
}
}
6.测试分析
基于xml配置模拟日志信息
1.在pom.xml中引入jar包坐标依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-aop</artifactId>
<groupId>xjit</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-aop-xml</artifactId>
<packaging>jar</packaging>
<modules>
<module>spring-aop-zj</module>
</modules>
<dependencies>
<dependency>
<!-- 解析aop切入表达式 * service.impl.*.*(..) -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
</dependencies>
</project>
2.创建service接口及实现类
package service;
public interface IAccountService {
void updateAccount(int i);
void saveAccount();
int deleteAccount();
}
package service.impl;
import service.IAccountService;
public class AccountServiceImpl implements IAccountService {
@Override
public void updateAccount(int i) {
System.out.println("更新了!");
}
@Override
public void saveAccount() {
System.out.println("保存了!");
}
@Override
public int deleteAccount() {
System.out.println("删除了!");
return 0;
}
}
3.创建日志工具类
package utils;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* 用于记录日志的工具类
*/
public class Logger {
/**
* 用于打印日志让其在切入点方法(业务层方法)执行之前执行
*/
public void printLog(){
System.out.println("printLog开始记录日志");
}
public void beforePrintLog(){
System.out.println("Logger中的beforePrintLog方法开始记录前置通知日志");
}
public void afterPrintLog(){
System.out.println("Logger中的afterPrintLog方法开始记录后置通知日志");
}
public void afterThrowingPrintLog(){
System.out.println("Logger中的afterThrowingPrintLog方法开始记录异常通知日志");
}
public void lastPrintLog(){
System.out.println("Logger中的lastPrintLog方法开始记录最后通知日志");
}
// spring的环绕通知:
public Object aroundPrintLogger(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("****Logger中的aroundPrintLogger方法开始记录通知日志****前置");
rtValue = pjp.proceed(args);//明确调用的业务层方法()
System.out.println("****Logger中的aroundPrintLogger方法开始记录通知日志****后置");
return rtValue;
} catch (Throwable t) {
System.out.println("****Logger中的aroundPrintLogger方法开始记录通知日志****异常");
throw new RuntimeException(t);
} finally {
System.out.println("****Logger中的aroundPrintLogger方法开始记录通知日志****最后");
}
}
}
4.在资源文件路径下创建配置文件bean.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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置spring的ioc把service对象配置进来-->
<bean id="accountService" class="service.impl.AccountServiceImpl"/>
<!-- spring基于xml的aop配置步骤:
1.将通知Bean交给spring来
2.使用aop:config标签表明开始aop的配置
3.使用aop:aspect标签表明配置切面
id属性:给切面提供一个唯一标识
ref属性:指定通知类bean的id
4.在aop:aspect标签的内部使用对应标签配置通知的类型
aop:before表示前置通知
method属性用于指定类中表示前置通知的方法
pointcut属性,用于指点切入表达式,该表达式的含义是对业务层的那些方法增强
切入点表达式的写法:
访问修饰符 返回值 包名.包名.类名.方法名(参数) public void service.impl.AccountServiceImpl.saveAccount()
全通配写法: * *..*.*(..)
* service.impl.*.*(..)
-->
<bean id="logger" class="utils.Logger"/>
<aop:config>
<!-- 配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置通知类型,建立通知方法和切入点的关联-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"/>
<aop:after-returning method="afterPrintLog" pointcut-ref="pt1"/>
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/>
<aop:after method="lastPrintLog" pointcut-ref="pt1"/>
<aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"/>
<aop:around method="aroundPrintLogger" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
</beans>
5.创建测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountService;
public class AOPTest {
public static void main(String[] args) {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取对象
IAccountService as = (IAccountService) ac.getBean("accountService");
//执行方法
as.saveAccount();
}
}