使用Spring Boot AOP處理方法的入?yún)⒑头祷刂?/h1>
更新時間:2021年08月16日 10:46:45 作者:Code0cean
這篇文章主要介紹了使用Spring Boot AOP處理方法的入?yún)⒑头祷刂担哂泻芎玫膮⒖純r值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
前言
IOC和AOP是Spring 中最重要的兩個模塊。這里練習(xí)一下如何使用Spring Boot AOP處理方法的入?yún)⒑头祷刂怠?/p>
Spring AOP的簡單介紹:
AOP(Aspect-Oriented Programming)面向切面編程,通過預(yù)編譯方式和運(yùn)行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)。AOP能夠?qū)⒛切┡c業(yè)務(wù)⽆關(guān),卻為業(yè)務(wù)模塊所共同調(diào)⽤的邏輯或責(zé)任(例如事務(wù)處理、⽇志管理、權(quán)限控制等)封裝起來,便于減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度,并有利于提高系統(tǒng)的可拓展性和可維護(hù)性。
Spring AOP就是基于動態(tài)代理的,如果要代理的對象,實現(xiàn)了某個接⼝,那么Spring AOP會使⽤JDK代理,去創(chuàng)建代理對象,⽽對于沒有實現(xiàn)接⼝的對象,就⽆法使⽤ JDK代理去進(jìn)⾏代理了,這時候Spring AOP會使⽤Cglib ,這時候Spring AOP會使⽤ Cglib代理 ⽣成⼀個被代理對象的⼦類來作為代理,如下圖所示:

一篇詳細(xì)介紹AOP的文章:細(xì)說Spring——AOP詳解(AOP概覽)
1. 需求場景
前段時間實習(xí),遇到了一個需求是這樣的:項目上線前,項目經(jīng)理要求有一個用戶私密信息的字段需要在數(shù)據(jù)庫中加密存儲,從數(shù)據(jù)庫讀取出來后需要解密,正常顯示到用戶界面中。
下面的DEMO中,模擬場景項目經(jīng)理突然覺得這個用戶的身份證號是用戶隱私需要進(jìn)行加密保存,保護(hù)用戶的隱私,
User類定義如下:
public class User {
private Integer id;
private String username;
private String password;
private String identityNum;
//省略getter、setter、toString方法
}
2. 解決方案
因為是臨時加的需求,考慮到多個實體類中都會有identityNum屬性,為了不侵入原本的業(yè)務(wù)代碼和數(shù)據(jù)處理代碼和業(yè)務(wù)代碼的解耦,一個比較好的方案是使用Spring AOP處理,以DAO層方法做切點(diǎn),處理字段的加密解密。
3. 代碼實現(xiàn)
下面使用Spring Boot+MyBatis實現(xiàn)DEMO,模擬上述場景和解決方案實現(xiàn)。
Controller層UserController類的代碼:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
@GetMapping
public List<User> getAllUsers(){
return userService.getAllUsers();
}
@PostMapping
public void save(@RequestBody User user){
userService.save(user);
}
}
Service層UserService類代碼:
@Service
public class UserService {
@Autowired
UserDao userDao;
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
public void save(User user) {
userDao.save(user);
}
}
Dao層UserDao接口實現(xiàn):
@Mapper
public interface UserDao {
List<User> getAllUsers();
void save(@Param("user") User user);
}
UserMapper.xml文件實現(xiàn):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.javahai.springbootdemo.dao.UserDao">
<insert id="save">
insert into user values (#{user.id},#{user.username},#{user.password},#{user.identityNum})
</insert>
<select id="getAllUsers" resultType="top.javahai.springbootdemo.entity.User">
select id,username,password,identity_num as identityNum from user
</select>
</mapper>
切面類UserInfoHandler實現(xiàn)如下,這里只是使用字符串截取的方法模擬加密代碼
使用環(huán)繞通知@Around注解實現(xiàn)
@Aspect
@Component
public class UserInfoHandler {
@Pointcut("execution(* top.javahai.springbootdemo.dao.UserDao.*(..))")
public void pointcut(){
}
@Around("pointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
//處理方法參數(shù),如果是User就進(jìn)行加密處理
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof List){
if (((List) arg).get(0) instanceof User){
((List<User>) arg).forEach(user->{
user.setIdentityNum("encode"+user.getIdentityNum());
});
}
}
if (arg instanceof User){
String identityNum = ((User) arg).getIdentityNum();
((User) arg).setIdentityNum("encode"+identityNum);
}
}
//執(zhí)行方法,獲取返回值
Object obj = joinPoint.proceed();
//處理方法返回值
if (obj instanceof List){
if (!((List) obj).isEmpty()){
if (((List) obj).get(0) instanceof User){
((List<User>) obj).forEach(data->{
data.setIdentityNum(data.getIdentityNum().substring(6));
});
}
}
}
return obj;
}
}
如果是在其他實體類中也存在identityNum身份證字段,則需要在@PointCut中定義多個切點(diǎn),另外處理的地方需要添加多個判斷。
定義多個切點(diǎn):
@Pointcut("execution(* top.javahai.springbootdemo.dao.UserDao.*(..)) ||" +
"execution(* top.javahai.springbootdemo.dao.ResumeDao.*(..))")
public void pointcut(){}
4. 測試
通過http://localhost:8080/users接口,將保存一個新的用戶數(shù)據(jù)到數(shù)據(jù)庫中

查看數(shù)據(jù)庫的存儲:

取出所有的用戶數(shù)據(jù):

從測試結(jié)果可以看到代碼可以正確的處理方法的入?yún)⒑头祷刂怠?/p>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
-
jar包運(yùn)行一段時間后莫名其妙掛掉線上問題及處理方案
這篇文章主要介紹了jar包運(yùn)行一段時間后莫名其妙掛掉線上問題及處理方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教 2023-09-09
-
Java經(jīng)典算法匯總之選擇排序(SelectionSort)
選擇排序也是比較簡單的一種排序方法,原理也比較容易理解,選擇排序在每次遍歷過程中只記錄下來最小的一個元素的下標(biāo),待全部比較結(jié)束之后,將最小的元素與未排序的那部分序列的最前面一個元素交換,這樣就降低了交換的次數(shù),提高了排序效率。 2016-04-04
-
java全角、半角字符的關(guān)系以及轉(zhuǎn)換詳解
這篇文章主要介紹了 2013-11-11
-
如何為Spring Cloud Gateway加上全局過濾器
這篇文章主要介紹了如何為Spring Cloud Gateway加上全局過濾器,幫助大家更好得理解和學(xué)習(xí)使用Gateway,感興趣的朋友可以了解下 2021-03-03
-
詳解Java虛擬機(jī)管理的內(nèi)存運(yùn)行時數(shù)據(jù)區(qū)域
這篇文章主要介紹了詳解Java虛擬機(jī)管理的內(nèi)存運(yùn)行時數(shù)據(jù)區(qū)域的相關(guān)資料,需要的朋友可以參考下 2017-03-03
-
Springboot中實現(xiàn)策略模式+工廠模式的方法
這篇文章主要介紹了Springboot中實現(xiàn)策略模式+工廠模式,具體策略模式和工廠模式的UML我就不給出來了,使用這個這兩個模式主要是防止程序中出現(xiàn)大量的IF ELSE IF ELSE....,接下來咱們直接實現(xiàn)Springboot策略模式工廠模式 2022-03-03
最新評論
前言
IOC和AOP是Spring 中最重要的兩個模塊。這里練習(xí)一下如何使用Spring Boot AOP處理方法的入?yún)⒑头祷刂怠?/p>
Spring AOP的簡單介紹:
AOP(Aspect-Oriented Programming)面向切面編程,通過預(yù)編譯方式和運(yùn)行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)。AOP能夠?qū)⒛切┡c業(yè)務(wù)⽆關(guān),卻為業(yè)務(wù)模塊所共同調(diào)⽤的邏輯或責(zé)任(例如事務(wù)處理、⽇志管理、權(quán)限控制等)封裝起來,便于減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度,并有利于提高系統(tǒng)的可拓展性和可維護(hù)性。
Spring AOP就是基于動態(tài)代理的,如果要代理的對象,實現(xiàn)了某個接⼝,那么Spring AOP會使⽤JDK代理,去創(chuàng)建代理對象,⽽對于沒有實現(xiàn)接⼝的對象,就⽆法使⽤ JDK代理去進(jìn)⾏代理了,這時候Spring AOP會使⽤Cglib ,這時候Spring AOP會使⽤ Cglib代理 ⽣成⼀個被代理對象的⼦類來作為代理,如下圖所示:
一篇詳細(xì)介紹AOP的文章:細(xì)說Spring——AOP詳解(AOP概覽)
1. 需求場景
前段時間實習(xí),遇到了一個需求是這樣的:項目上線前,項目經(jīng)理要求有一個用戶私密信息的字段需要在數(shù)據(jù)庫中加密存儲,從數(shù)據(jù)庫讀取出來后需要解密,正常顯示到用戶界面中。
下面的DEMO中,模擬場景項目經(jīng)理突然覺得這個用戶的身份證號是用戶隱私需要進(jìn)行加密保存,保護(hù)用戶的隱私,
User類定義如下:
public class User { private Integer id; private String username; private String password; private String identityNum; //省略getter、setter、toString方法 }
2. 解決方案
因為是臨時加的需求,考慮到多個實體類中都會有identityNum屬性,為了不侵入原本的業(yè)務(wù)代碼和數(shù)據(jù)處理代碼和業(yè)務(wù)代碼的解耦,一個比較好的方案是使用Spring AOP處理,以DAO層方法做切點(diǎn),處理字段的加密解密。
3. 代碼實現(xiàn)
下面使用Spring Boot+MyBatis實現(xiàn)DEMO,模擬上述場景和解決方案實現(xiàn)。
Controller層UserController類的代碼:
@RestController @RequestMapping("/users") public class UserController { @Autowired UserService userService; @GetMapping public List<User> getAllUsers(){ return userService.getAllUsers(); } @PostMapping public void save(@RequestBody User user){ userService.save(user); } }
Service層UserService類代碼:
@Service public class UserService { @Autowired UserDao userDao; public List<User> getAllUsers() { return userDao.getAllUsers(); } public void save(User user) { userDao.save(user); } }
Dao層UserDao接口實現(xiàn):
@Mapper public interface UserDao { List<User> getAllUsers(); void save(@Param("user") User user); }
UserMapper.xml文件實現(xiàn):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="top.javahai.springbootdemo.dao.UserDao"> <insert id="save"> insert into user values (#{user.id},#{user.username},#{user.password},#{user.identityNum}) </insert> <select id="getAllUsers" resultType="top.javahai.springbootdemo.entity.User"> select id,username,password,identity_num as identityNum from user </select> </mapper>
切面類UserInfoHandler實現(xiàn)如下,這里只是使用字符串截取的方法模擬加密代碼
使用環(huán)繞通知@Around注解實現(xiàn)
@Aspect @Component public class UserInfoHandler { @Pointcut("execution(* top.javahai.springbootdemo.dao.UserDao.*(..))") public void pointcut(){ } @Around("pointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { //處理方法參數(shù),如果是User就進(jìn)行加密處理 Object[] args = joinPoint.getArgs(); for (Object arg : args) { if (arg instanceof List){ if (((List) arg).get(0) instanceof User){ ((List<User>) arg).forEach(user->{ user.setIdentityNum("encode"+user.getIdentityNum()); }); } } if (arg instanceof User){ String identityNum = ((User) arg).getIdentityNum(); ((User) arg).setIdentityNum("encode"+identityNum); } } //執(zhí)行方法,獲取返回值 Object obj = joinPoint.proceed(); //處理方法返回值 if (obj instanceof List){ if (!((List) obj).isEmpty()){ if (((List) obj).get(0) instanceof User){ ((List<User>) obj).forEach(data->{ data.setIdentityNum(data.getIdentityNum().substring(6)); }); } } } return obj; } }
如果是在其他實體類中也存在identityNum身份證字段,則需要在@PointCut中定義多個切點(diǎn),另外處理的地方需要添加多個判斷。
定義多個切點(diǎn):
@Pointcut("execution(* top.javahai.springbootdemo.dao.UserDao.*(..)) ||" + "execution(* top.javahai.springbootdemo.dao.ResumeDao.*(..))") public void pointcut(){}
4. 測試
通過http://localhost:8080/users接口,將保存一個新的用戶數(shù)據(jù)到數(shù)據(jù)庫中
查看數(shù)據(jù)庫的存儲:
取出所有的用戶數(shù)據(jù):
從測試結(jié)果可以看到代碼可以正確的處理方法的入?yún)⒑头祷刂怠?/p>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
jar包運(yùn)行一段時間后莫名其妙掛掉線上問題及處理方案
這篇文章主要介紹了jar包運(yùn)行一段時間后莫名其妙掛掉線上問題及處理方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09Java經(jīng)典算法匯總之選擇排序(SelectionSort)
選擇排序也是比較簡單的一種排序方法,原理也比較容易理解,選擇排序在每次遍歷過程中只記錄下來最小的一個元素的下標(biāo),待全部比較結(jié)束之后,將最小的元素與未排序的那部分序列的最前面一個元素交換,這樣就降低了交換的次數(shù),提高了排序效率。2016-04-04java全角、半角字符的關(guān)系以及轉(zhuǎn)換詳解
這篇文章主要介紹了2013-11-11如何為Spring Cloud Gateway加上全局過濾器
這篇文章主要介紹了如何為Spring Cloud Gateway加上全局過濾器,幫助大家更好得理解和學(xué)習(xí)使用Gateway,感興趣的朋友可以了解下2021-03-03詳解Java虛擬機(jī)管理的內(nèi)存運(yùn)行時數(shù)據(jù)區(qū)域
這篇文章主要介紹了詳解Java虛擬機(jī)管理的內(nèi)存運(yùn)行時數(shù)據(jù)區(qū)域的相關(guān)資料,需要的朋友可以參考下2017-03-03Springboot中實現(xiàn)策略模式+工廠模式的方法
這篇文章主要介紹了Springboot中實現(xiàn)策略模式+工廠模式,具體策略模式和工廠模式的UML我就不給出來了,使用這個這兩個模式主要是防止程序中出現(xiàn)大量的IF ELSE IF ELSE....,接下來咱們直接實現(xiàn)Springboot策略模式工廠模式2022-03-03