spring aop 和自定義注解的使用(spring boot)
- 在spring boot 的配置文件中開啟spring aop
# spring aop
spring.aop.auto=true
spring.aop.proxy-target-class=true
- 自定義注解
package comleader.datagovernancesys.auth;
import org.springframework.context.annotation.Description;
import java.lang.annotation.*;
/**
* 這是一個用于認證授權(quán)的注解
*/
@Retention(RetentionPolicy.RUNTIME) // 注解在運行時才會執(zhí)行
@Target(ElementType.METHOD) // 注解只能使用在方法上
@Inherited
@Documented
@Description("用于認證授權(quán)")
public @interface Auth {
}
- 定義切入點和要執(zhí)行的方法
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 使用spring aop 實現(xiàn)認證操作
*/
@Component
@Aspect
public class Authentication {
/**
* 以設(shè)定的注解作為切入點
*/
@Pointcut(value = "@annotation(comleader.datagovernancesys.auth.Auth)")
public void authenticationPointCut(){}
/**
* 在加了@comleader.datagovernancesys.auth.Auth 注解的方法之前執(zhí)行下面的方法
* @param j
*/
@Before(value = "authenticationPointCut()")
public void authentication(JoinPoint j){
System.out.println(" 認證通過 ! ---------------------------------------------------------------------");
}
}
- 測試
package comleader.datagovernancesys.controlelr;
import comleader.datagovernancesys.auth.Auth;
import org.springframework.web.bind.annotation.*;
/**
* @Program: data-governance-sys
* @Author: 努力就是魅力
* @Since: 2019-03-04 20:32
* Description: TODO
**/
@RestController
@RequestMapping(value = "/hdfs")
public class HdfsMetaDataController {
@GetMapping(value = "/aa")
@Auth
public String test(){
return "success";
}
}
頁面訪問地址:http://localhost:8080/hdfs/aa
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。