使用Spring Boot AOP處理方法的入?yún)⒑头祷刂?/h1>
瀏覽:29日期:2023-12-03 14:32:58
目錄前言Spring AOP的簡(jiǎn)單介紹:1. 需求場(chǎng)景User類定義如下:2. 解決方案3. 代碼實(shí)現(xiàn)Controller層UserController類的代碼:Service層UserService類代碼:Dao層UserDao接口實(shí)現(xiàn):UserMapper.xml文件實(shí)現(xiàn):使用環(huán)繞通知@Around注解實(shí)現(xiàn)定義多個(gè)切點(diǎn):4. 測(cè)試查看數(shù)據(jù)庫(kù)的存儲(chǔ):取出所有的用戶數(shù)據(jù):前言IOC和AOP是Spring 中最重要的兩個(gè)模塊。這里練習(xí)一下如何使用Spring Boot AOP處理方法的入?yún)⒑头祷刂怠?/p>Spring AOP的簡(jiǎn)單介紹:
AOP(Aspect-Oriented Programming)面向切面編程,通過(guò)預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)。AOP能夠?qū)⒛切┡c業(yè)務(wù)⽆關(guān),卻為業(yè)務(wù)模塊所共同調(diào)⽤的邏輯或責(zé)任(例如事務(wù)處理、⽇志管理、權(quán)限控制等)封裝起來(lái),便于減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度,并有利于提高系統(tǒng)的可拓展性和可維護(hù)性。
Spring AOP就是基于動(dòng)態(tài)代理的,如果要代理的對(duì)象,實(shí)現(xiàn)了某個(gè)接⼝,那么Spring AOP會(huì)使⽤JDK代理,去創(chuàng)建代理對(duì)象,⽽對(duì)于沒(méi)有實(shí)現(xiàn)接⼝的對(duì)象,就⽆法使⽤ JDK代理去進(jìn)⾏代理了,這時(shí)候Spring AOP會(huì)使⽤Cglib ,這時(shí)候Spring AOP會(huì)使⽤ Cglib代理 ⽣成⼀個(gè)被代理對(duì)象的⼦類來(lái)作為代理,如下圖所示:
![使用Spring Boot AOP處理方法的入?yún)⒑头祷刂? src=]()
一篇詳細(xì)介紹AOP的文章:細(xì)說(shuō)Spring——AOP詳解(AOP概覽)
1. 需求場(chǎng)景前段時(shí)間實(shí)習(xí),遇到了一個(gè)需求是這樣的:項(xiàng)目上線前,項(xiàng)目經(jīng)理要求有一個(gè)用戶私密信息的字段需要在數(shù)據(jù)庫(kù)中加密存儲(chǔ),從數(shù)據(jù)庫(kù)讀取出來(lái)后需要解密,正常顯示到用戶界面中。
下面的DEMO中,模擬場(chǎng)景項(xiàng)目經(jīng)理突然覺(jué)得這個(gè)用戶的身份證號(hào)是用戶隱私需要進(jìn)行加密保存,保護(hù)用戶的隱私,
User類定義如下:public class User { private Integer id; private String username; private String password; private String identityNum; //省略getter、setter、toString方法}2. 解決方案
因?yàn)槭桥R時(shí)加的需求,考慮到多個(gè)實(shí)體類中都會(huì)有identityNum屬性,為了不侵入原本的業(yè)務(wù)代碼和數(shù)據(jù)處理代碼和業(yè)務(wù)代碼的解耦,一個(gè)比較好的方案是使用Spring AOP處理,以DAO層方法做切點(diǎn),處理字段的加密解密。
3. 代碼實(shí)現(xiàn)下面使用Spring Boot+MyBatis實(shí)現(xiàn)DEMO,模擬上述場(chǎng)景和解決方案實(shí)現(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類代碼:
@Servicepublic class UserService { @Autowired UserDao userDao; public List<User> getAllUsers() {return userDao.getAllUsers(); } public void save(User user) {userDao.save(user); }}Dao層UserDao接口實(shí)現(xiàn):
@Mapperpublic interface UserDao { List<User> getAllUsers(); void save(@Param('user') User user);}UserMapper.xml文件實(shí)現(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 resultType='top.javahai.springbootdemo.entity.User'>select id,username,password,identity_num as identityNum from user </select></mapper>
切面類UserInfoHandler實(shí)現(xiàn)如下,這里只是使用字符串截取的方法模擬加密代碼
使用環(huán)繞通知@Around注解實(shí)現(xiàn)@Aspect@Componentpublic 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; }}
如果是在其他實(shí)體類中也存在identityNum身份證字段,則需要在@PointCut中定義多個(gè)切點(diǎn),另外處理的地方需要添加多個(gè)判斷。
定義多個(gè)切點(diǎn): @Pointcut('execution(* top.javahai.springbootdemo.dao.UserDao.*(..)) ||' + 'execution(* top.javahai.springbootdemo.dao.ResumeDao.*(..))') public void pointcut(){}4. 測(cè)試
通過(guò)http://localhost:8080/users接口,將保存一個(gè)新的用戶數(shù)據(jù)到數(shù)據(jù)庫(kù)中
![使用Spring Boot AOP處理方法的入?yún)⒑头祷刂? src=]()
查看數(shù)據(jù)庫(kù)的存儲(chǔ):![使用Spring Boot AOP處理方法的入?yún)⒑头祷刂? src=]()
取出所有的用戶數(shù)據(jù):![使用Spring Boot AOP處理方法的入?yún)⒑头祷刂? src=]()
從測(cè)試結(jié)果可以看到代碼可以正確的處理方法的入?yún)⒑头祷刂怠?/p>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
標(biāo)簽:
Spring
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析4. SharePoint Server 2019新特性介紹5. .Net core 的熱插拔機(jī)制的深入探索及卸載問(wèn)題求救指南6. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問(wèn)題7. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題8. ASP編碼必備的8條原則9. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)10. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp
IOC和AOP是Spring 中最重要的兩個(gè)模塊。這里練習(xí)一下如何使用Spring Boot AOP處理方法的入?yún)⒑头祷刂怠?/p>Spring AOP的簡(jiǎn)單介紹:
AOP(Aspect-Oriented Programming)面向切面編程,通過(guò)預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)。AOP能夠?qū)⒛切┡c業(yè)務(wù)⽆關(guān),卻為業(yè)務(wù)模塊所共同調(diào)⽤的邏輯或責(zé)任(例如事務(wù)處理、⽇志管理、權(quán)限控制等)封裝起來(lái),便于減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度,并有利于提高系統(tǒng)的可拓展性和可維護(hù)性。
Spring AOP就是基于動(dòng)態(tài)代理的,如果要代理的對(duì)象,實(shí)現(xiàn)了某個(gè)接⼝,那么Spring AOP會(huì)使⽤JDK代理,去創(chuàng)建代理對(duì)象,⽽對(duì)于沒(méi)有實(shí)現(xiàn)接⼝的對(duì)象,就⽆法使⽤ JDK代理去進(jìn)⾏代理了,這時(shí)候Spring AOP會(huì)使⽤Cglib ,這時(shí)候Spring AOP會(huì)使⽤ Cglib代理 ⽣成⼀個(gè)被代理對(duì)象的⼦類來(lái)作為代理,如下圖所示:
一篇詳細(xì)介紹AOP的文章:細(xì)說(shuō)Spring——AOP詳解(AOP概覽)
1. 需求場(chǎng)景前段時(shí)間實(shí)習(xí),遇到了一個(gè)需求是這樣的:項(xiàng)目上線前,項(xiàng)目經(jīng)理要求有一個(gè)用戶私密信息的字段需要在數(shù)據(jù)庫(kù)中加密存儲(chǔ),從數(shù)據(jù)庫(kù)讀取出來(lái)后需要解密,正常顯示到用戶界面中。
下面的DEMO中,模擬場(chǎng)景項(xiàng)目經(jīng)理突然覺(jué)得這個(gè)用戶的身份證號(hào)是用戶隱私需要進(jìn)行加密保存,保護(hù)用戶的隱私,
User類定義如下:public class User { private Integer id; private String username; private String password; private String identityNum; //省略getter、setter、toString方法}2. 解決方案
因?yàn)槭桥R時(shí)加的需求,考慮到多個(gè)實(shí)體類中都會(huì)有identityNum屬性,為了不侵入原本的業(yè)務(wù)代碼和數(shù)據(jù)處理代碼和業(yè)務(wù)代碼的解耦,一個(gè)比較好的方案是使用Spring AOP處理,以DAO層方法做切點(diǎn),處理字段的加密解密。
3. 代碼實(shí)現(xiàn)下面使用Spring Boot+MyBatis實(shí)現(xiàn)DEMO,模擬上述場(chǎng)景和解決方案實(shí)現(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類代碼:
@Servicepublic class UserService { @Autowired UserDao userDao; public List<User> getAllUsers() {return userDao.getAllUsers(); } public void save(User user) {userDao.save(user); }}Dao層UserDao接口實(shí)現(xiàn):
@Mapperpublic interface UserDao { List<User> getAllUsers(); void save(@Param('user') User user);}UserMapper.xml文件實(shí)現(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 resultType='top.javahai.springbootdemo.entity.User'>select id,username,password,identity_num as identityNum from user </select></mapper>
切面類UserInfoHandler實(shí)現(xiàn)如下,這里只是使用字符串截取的方法模擬加密代碼
使用環(huán)繞通知@Around注解實(shí)現(xiàn)@Aspect@Componentpublic 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; }}
如果是在其他實(shí)體類中也存在identityNum身份證字段,則需要在@PointCut中定義多個(gè)切點(diǎn),另外處理的地方需要添加多個(gè)判斷。
定義多個(gè)切點(diǎn):@Pointcut('execution(* top.javahai.springbootdemo.dao.UserDao.*(..)) ||' + 'execution(* top.javahai.springbootdemo.dao.ResumeDao.*(..))') public void pointcut(){}4. 測(cè)試
通過(guò)http://localhost:8080/users接口,將保存一個(gè)新的用戶數(shù)據(jù)到數(shù)據(jù)庫(kù)中
從測(cè)試結(jié)果可以看到代碼可以正確的處理方法的入?yún)⒑头祷刂怠?/p>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
