弊端:代码已经开发完成,后期需要添加公共功能,就需要改动原来的代码。
需求:可不可以在不修改原来代码的情况下,额外的添加其他功能。
解决方法:AOP
AOP 为 Aspect Oriented Programming 的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP 是 OOP 的延续,是软件开发中的一个热点,是 java 开发中的一个重要内容。利用 AOP 可以对业务逻辑和非业务逻辑进行隔离,从而使得各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP,面向切面编程,面向切面就是动态考虑程序的运行。AOP是基于动态代理,是动态代理的规范化,让动态代理实现步骤固定化。
动态代理作用:在目标源代码不改变的情况下,增加功能;减少代码的重复;专注业务逻辑代码;解耦合,让事务和业务分离。
AOP(Aspect Oriented Programming):
Aspect :切面,给目标类增加的功能,就是切面,向日志,事务… 切面一般都是非业务方法,独立使用的。
Oriented :面向
Programming:编程。
面向切面的理解:需要在项目分析时,找出切面,合理的安排切面执行的时间,执行的位置在哪个类。
Aspect:切面,表示增强的功能,就是一堆代码,完成某个功能,非业务功能。常见的切面有日志,事务,统计信息,参数检查,权限验证。
JoinPoint:链接点,链接业务方法和切面的位置,类中可以被增强的方法,这个方法就被称为连接点
Pointcut:切入点,类中有很多方法可以被增强,但实际中只有 add 和 update被增了,那么 add 和 update 方法就被称为切入点(实际实现的连接点)
目标对象:给哪个类的方法增加功能,这个类是目标对象
Advice:通知,通知表示切面功能执行的时间,通知是指一个切面在特定的连接点要做的事情(增强的功能)。通知分为方法执行前通知,方法执行后通知,环绕通知等。
AOP实现框架:
首先需要下载AOP相关jar
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.2.RELEASEversion>
dependency>
<bean id="commentUtil" class="com.ffyc.spring.util.CommentUtil">bean>
<aop:config>
<aop:pointcut id="saveAdmin" expression="execution(* com.ffyc.spring.dao.AdminDao.saveAdmin())"/>
<aop:aspect ref="commentUtil">
<aop:before method="saveLog" pointcut-ref="saveAdmin">aop:before>
<aop:after method="saveLog" pointcut-ref="saveAdmin">aop:after>
<aop:after-throwing method="exceptionAdvice" pointcut-ref="saveAdmin" throwing="e" />
<aop:around method="aroundAdvice" pointcut-ref="adduser"/>
aop:aspect>
aop:config>
@Component
@Aspect//配置切面
public class CommentUtil {
//不能在一个方法上出现两个通知
@Before("execution(* com.ffyc.spring.dao.AdminDao.*(..))")
//@Before @After @Around @AfterReturning的写法都一样
public void saveLog(){
System.out.println("Before");
}
@AfterThrowing(value = "execution(* com.ffyc.spring.dao.AdminDao.*(..))",throwing = "e")
public void exceptionAdvice(Exception e){
System.out.println("异常:"+e.getMessage());
}
}