Spring AOP面向切面編程實(shí)現(xiàn)原理方法詳解
1. 什么是AOP
AOP (Aspect Oriented Programming)意為:面向切面編程,通過(guò)預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)在不修改源代碼的情況下,給程序動(dòng)態(tài)統(tǒng)一添加功能的一種技術(shù),可以理解成動(dòng)態(tài)代理。是Spring框架中的一個(gè)重要內(nèi)容。利用 AOP 可以對(duì)業(yè)務(wù)邏輯的各個(gè)部分進(jìn)行隔離,使業(yè)務(wù)邏輯各部分之間的耦合度降低,提高程序的可重用性,同時(shí)提高開(kāi)發(fā)的效率
2. Spring AOP
①. AOP 在Spring中的作用
提供聲明式事務(wù);允許用戶自定義切面
②. AOP 的基本概念
橫切關(guān)注點(diǎn):跨越應(yīng)用程序多個(gè)模塊的方法或功能。即與我們業(yè)務(wù)邏輯無(wú)關(guān),但需要我們關(guān)注的部分就是橫切關(guān)注點(diǎn)。如日志 , 安全 , 緩存 , 事務(wù)等等 ....
- Aspect(切面):橫切關(guān)注點(diǎn)被模塊化的特殊對(duì)象。通常是一個(gè)類(lèi),里面可以定義切入點(diǎn)和通知
- Weaving(織入):把切面(aspect)連接到其它的應(yīng)用程序類(lèi)型或者對(duì)象上,并創(chuàng)建一個(gè)被通知(advised)的對(duì)象。 這些可以在編譯時(shí),類(lèi)加載時(shí)和運(yùn)行時(shí)完成。Spring和其它純Java AOP框架一樣,在運(yùn)行時(shí)完成織入
- Advice(通知):AOP在特定的切入點(diǎn)上執(zhí)行的增強(qiáng)處理,是切面必須要完成的工作,也是類(lèi)中的一個(gè)方法
- Target(目標(biāo)):被通知對(duì)象
- AOP(代理):AOP框架創(chuàng)建的對(duì)象,代理就是目標(biāo)對(duì)象的加強(qiáng)。Spring中的 AOP 代理可以是 JDK 動(dòng)態(tài)代理,也可以是 CGLIB 代理,前者基于接口,后者基于子類(lèi)
- JointPoint(連接點(diǎn)):程序執(zhí)行過(guò)程中明確的點(diǎn),一般是方法的調(diào)用
- Pointcut(切入點(diǎn)):就是帶有通知的連接點(diǎn),與切入點(diǎn)匹配的執(zhí)行點(diǎn)
③. 使用Spring實(shí)現(xiàn)Aop
前提
使用AOP織入,需要導(dǎo)入一個(gè)依賴(lài)包
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency>
實(shí)現(xiàn)Aop的三種方式
方式一:通過(guò) Spring API 實(shí)現(xiàn)【主要是springAPI接口實(shí)現(xiàn)】
首先編寫(xiě)業(yè)務(wù)接口和實(shí)現(xiàn)類(lèi)
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一個(gè)用戶");
}
public void delete() {
System.out.println("刪除了一個(gè)用戶");
}
public void update() {
System.out.println("更新了一個(gè)用戶");
}
public void select() {
System.out.println("查詢(xún)了一個(gè)用戶");
}
}
接著編寫(xiě)增強(qiáng)類(lèi),這里寫(xiě)兩個(gè):前置增強(qiáng)Log和后置增強(qiáng)AfterLog
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method: 要執(zhí)行的目標(biāo)對(duì)象的方法
//args: 參數(shù)
//target: 目標(biāo)對(duì)象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被執(zhí)行了");
}
}
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue;返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("執(zhí)行了"+method.getName()+"方法,返回結(jié)果為:"+returnValue);
}
}
最后在Spring的文件中注冊(cè)( applicationContext.xml ),并實(shí)現(xiàn)AOP切入,注意導(dǎo)入約束
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注冊(cè)bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式一:使用原生Spring API接口 -->
<!--配置aop:需要導(dǎo)入aop的約束-->
<aop:config>
<!--切入點(diǎn):expression:表達(dá)式,execution(要執(zhí)行的位置! * * * * *) -->
<aop:pointcut id="pointcut" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
<!--執(zhí)行環(huán)繞; advice-ref執(zhí)行方法 . pointcut-ref切入點(diǎn)-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
進(jìn)行測(cè)試:
import com.lf.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1 = (UserService) context.getBean("userService");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
運(yùn)行結(jié)果:
com.lf.service.UserServiceImpl的add被執(zhí)行了
增加了一個(gè)用戶
執(zhí)行了add方法,返回結(jié)果為:null
方式二:自定義類(lèi)實(shí)現(xiàn)AOP【主要是切面定義】
目標(biāo)業(yè)務(wù)類(lèi)不變,還是方式一中的UserServiceImpl
寫(xiě)入一個(gè)切入類(lèi)
public class DiyPointCut {
public void before(){
System.out.println("========方法執(zhí)行前=========");
}
public void after(){
System.out.println("========方法執(zhí)行后=========");
}
}
在Spring中配置(applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注冊(cè)bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式二:自定義類(lèi)-->
<bean id="diy" class="com.lf.diy.DiyPointCut"/>
<aop:config>
<!--自定義切面, ref 要引用的類(lèi)-->
<aop:aspect ref="diy">
<!--切入點(diǎn)-->
<aop:pointcut id="point" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
在上面的 MyTest.java 中測(cè)試,得到結(jié)果:
========方法執(zhí)行前=========
增加了一個(gè)用戶
========方法執(zhí)行后=========
方式三:使用注解實(shí)現(xiàn)【多用】
編寫(xiě)一個(gè)注解實(shí)現(xiàn)的增強(qiáng)類(lèi)
package com.lf.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //標(biāo)注這個(gè)類(lèi)是一個(gè)切面
public class AnnotationPointCut {
@Before("execution(* com.lf.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=====方法執(zhí)行前======");
}
@After("execution(* com.lf.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=====方法執(zhí)行后======");
}
//在環(huán)繞增強(qiáng)中,我們可以給定一個(gè)參數(shù),代表我們要獲取處理切入的點(diǎn);
@Around("execution(* com.lf.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("環(huán)繞前");
Signature signature = jp.getSignature();//獲得簽名
System.out.println("signature:"+signature);
Object proceed = jp.proceed(); //執(zhí)行方法
System.out.println("環(huán)繞后");
System.out.println(proceed);
}
}
在Spring配置文件中,注冊(cè)bean,并增加支持注解的配置
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注冊(cè)bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式三-->
<bean id="annotationPointCut" class="com.lf.diy.AnnotationPointCut"/>
<!--開(kāi)啟注解支持! JDK(默認(rèn) proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
</beans>
在 MyTest.java 中測(cè)試
import com.lf.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
得到結(jié)果:
環(huán)繞前
signature:void com.lf.service.UserService.add()
=====方法執(zhí)行前======
增加了一個(gè)用戶
=====方法執(zhí)行后======
環(huán)繞后
null
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
輸出java進(jìn)程的jstack信息示例分享 通過(guò)線程堆棧信息分析java線程
通過(guò)ps到j(luò)ava進(jìn)程號(hào)將進(jìn)程的jstack信息輸出。jstack信息是java進(jìn)程的線程堆棧信息,通過(guò)該信息可以分析java的線程阻塞等問(wèn)題。2014-01-01
Struts1教程之ActionMapping_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Struts1教程之ActionMapping,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法AES定義與用法詳解
這篇文章主要介紹了Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法AES,結(jié)合實(shí)例形式分析了對(duì)稱(chēng)加密算法AES的定義、特點(diǎn)、用法及使用場(chǎng)景,需要的朋友可以參考下2018-04-04
Jar包如何導(dǎo)入本地maven倉(cāng)庫(kù)
將本地jar包導(dǎo)入本地maven倉(cāng)庫(kù),可以通過(guò)maven命令-Dfile、-DgroupId、-DartifactId、-Dversion、-Dpackaging指定jar包的詳細(xì)信息,然后執(zhí)行命令即可2024-11-11
淺談Java的虛擬機(jī)結(jié)構(gòu)以及虛擬機(jī)內(nèi)存的優(yōu)化
這篇文章主要介紹了Java的虛擬機(jī)結(jié)構(gòu)以及虛擬機(jī)內(nèi)存的優(yōu)化,講到了JVM的堆和??臻g及GC垃圾回收等重要知識(shí),需要的朋友可以參考下2016-03-03
Java如何正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題
這篇文章主要介紹了Java如何正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題,2023-07-07
通常HTTP消息包括客戶機(jī)向服務(wù)器的請(qǐng)求消息和服務(wù)器向客戶機(jī)的響應(yīng)消息,今天來(lái)講解下正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題,需要的朋友可以參考下
Java中實(shí)現(xiàn)文件上傳下載的三種解決方案(推薦)
這篇文章主要介紹了Java中實(shí)現(xiàn)文件上傳下載的三種解決方案的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07
Java 實(shí)現(xiàn)定時(shí)任務(wù)的三種方法
這篇文章主要介紹了Java 實(shí)現(xiàn)定時(shí)任務(wù)的三種方法,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03

