面向切面編程
面向切面編程,可以將與業務無關但是需要被各個業務模組共同調用的邏輯抽取出來,以切面的方式切入到代碼中,從而降低系統中代碼的耦合度,減少重複的程式碼。
Spring AOP是透過預編譯方式和運行期間動態代理實現程式面向切面程式設計
AOP的底層原理實作
AOP底層使用動態代理完成需求,為需要增加增強功能的類別來產生代理類,有兩種產生代理類別的方式,對於被代理類別(即需要增強的類別),如果:
#實作了接口,使用JDK動態代理,產生的代理類別會使用其介面沒有實作接口,
使用CGlib動態代理,產生的代理類別會整合被代理類別
AOP的相關術語
#連接點:在被代理(被增強)的類別中的方法
切入點:實際上需要被增強的方法
##通知:要增強的邏輯代碼
前通知:在主體功能執行前執行
後置通知:在主題功能執行之後執行
環繞通知:在主體功能執行前後執行
#異常通知:在主題功能執行出現異常時執行
#最終通知:主體功能無論執行是否成功都會執行
切面:切入點和切面的結合,即被增強的方法和增強的功能組成切面
註解:
#@Aspect: 宣告某個類別是切面,寫通知、切入點
@Before: 對應前置通知
@AfterReturning: 對應後置通知
@Around: 對應環繞通知
- ##@AfterThrowing:
對應例外通知
- @After:
對應最終通知
- @Pointcut:
聲明切入點,標註在一個方法上可以讓表達式更簡潔
- execution([權限修飾符][傳回類型][類別完全路徑].[方法名稱][參數清單類型])
- execution(* com.xxx.ABC. add()),對ABC類別的方法進行增強
實作介面鑑權
1. 設定yml檔案
設定介面鑑權帳密account: infos: - account: xinchao secret: admin2. 讀取帳密配置
@Data public class SecretInfo { private String account; private String secret; }
3.寫介面鑑權方法
@Configuration @ConfigurationProperties("account") public class SecretConfig { private List<SecretInfo> infos; private Map<String, SecretInfo> map; private Map<String, TokenInfo> tokenMap = new HashMap<>(); public void setInfos(List<SecretInfo> infos) { this.infos = infos; map = infos.stream().collect(Collectors.toMap(SecretInfo::getAccount, Function.identity())); } public synchronized String getToken(String account, String secret) { SecretInfo info = map.get(account); if (info == null) { throw new BusinessException("无效账号"); } if (!StringUtils.equals(info.getSecret(), secret)) { throw new BusinessException("无效密码"); } TokenInfo tokenInfo = tokenMap.get(account); if (tokenInfo != null && tokenInfo.getToken() != null) { return tokenInfo.getToken(); } tokenInfo = new TokenInfo(); String uuid = UUID.randomUUID().toString(); tokenInfo.setToken(uuid); tokenInfo.setCreateDate(LocalDateTime.now()); tokenInfo.setExpireDate(LocalDateTime.now().plusHours(2)); tokenMap.put(account,tokenInfo); return tokenInfo.getToken(); } public boolean checkCaptcha(String captcha) { return tokenMap.values().stream().anyMatch(e->StringUtils.equals(e.getToken(),captcha)); } }
@Data public class TokenInfo { private LocalDateTime createDate; private LocalDateTime expireDate; private String token; public String getToken() { if (LocalDateTime.now().isBefore(expireDate)) { return token; } return null; } public boolean verification(String token) { return Objects.equals(this.token, token); } }
4. 寫AOP
首先,編寫一個註解來標識不需要鑑權@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CaptchaIgnoreAop { }@Slf4j @Aspect @Component @Order(2) public class CaptchaAop { @Value("${spring.profiles.active:dev}") private String env; @Autowired private SecretConfig config; @Pointcut("execution(public * com.herenit.phsswitch.controller.impl..*.*(..))" + "&&@annotation(org.springframework.web.bind.annotation.PostMapping)" + "&&!@annotation(com.herenit.phsswitch.aop.CaptchaIgnoreAop)") public void tokenAop() { } @Around("tokenAop()") public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); if (args.length == 0 || !(args[0] instanceof RequestWrapper) || "test,dev".contains(env)) { log.info("当前环境无需校验token"); return joinPoint.proceed(); } String captcha = ((RequestWrapper) joinPoint.getArgs()[0]).getCaptcha(); if (!config.checkCaptcha(captcha)) { throw new BusinessException("captcha无效"); } return joinPoint.proceed(); } }5.編寫介面測試
@PostMapping("/login") @CaptchaIgnoreAop public ResponseWrapper login(@RequestBody JSONObject userInfo) { String token = config.getToken(userInfo.getString("loginName") , userInfo.getString("password")); JSONObject result = new JSONObject(); result.put("platformAccessToken", token); return ResponseWrapper.success(result); }
使用此介面能夠在記憶體中建立一個令牌,並將其傳回給前端。之後我們在調其他介面時傳入這個token進行鑑權即可。傳入的位置是captcha字段
public class RequestWrapper<T> implements Serializable { private static final long serialVersionUID = 8988706670118918321L; public RequestWrapper() { super(); } private T args; private String captcha; private String funcode; public T getArgs() { return args; } public void setArgs(T args) { this.args = args; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } public String getFuncode() { return funcode; } public void setFuncode(String funcode) { this.funcode = funcode; } }
以上是怎麼在SpringBoot中使用Spring AOP實作介面鑑權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver Mac版
視覺化網頁開發工具