切面编程的应用案例比较多,在统一的日志处理,鉴权过程中都会用的AOP原理,本文主要针对对进口的访问权限进行控制为例,说明
切面编程的使用;
1、使用Aspectj的方式进行切面编程;
2、编码环境,spring框架;
3、延伸的 spring中自定义注解的实现;
一、自定义注解:注解用来加在权限控制接口上进行注解处理
//在运行时执行 @Retention(RetentionPolicy.RUNTIME) //注解适用于方法 @Target({ElementType.METHOD}) @Documented @Inherited public @interface Function { //注解的name属性 String value() default ""; }
二、对注解进行切面处理
@Aspect @Component public class RoleAccessConfig { protected boolean isAccessOK(String functionName) { //权限查阅 return false; } protected boolean canAccess(String functionName) { if(functionName != null) { //总是允许访问 //针对名称进行权限查阅判断是否有权限 // if( isAccessOK(functionName) ) { System.out.println(" 具备删除权限 "); return true; }else { System.out.println(" 不具备删除权限 "); return false; } }else{ System.out.println(" 违法访问 "); return false ; } } /**对Controller进行安全和身份校验 */ @Around("within(@org.springframework.stereotype.Controller *) && @annotation (function)") public Object functionAccessCheck(final ProceedingJoinPoint pjp , Function function ) throws Throwable { if (function != null ) { //自动以注解获得注解信息 String functionName = function.value(); if( ! canAccess(functionName )) { //获得数字签名 Signature ms= pjp.getSignature(); //判断是否数据方法签名 if (!(ms instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } //转化为方法签名 MethodSignature msig = (MethodSignature) ms; throw new RuntimeException ("Can not Access !" + msig.getMethod() ); } //继续在切入点处进行操作,也就是有访问权限进入接口处理 Object o = pjp.proceed() ; return o ; }else { Object o = null; return o; } }
三、在spring配置文件中,开启AOP使用配置
<aop:aspectj-autoproxy proxy-target-class="true"/>
只配置这段会报:The prefix "aop" for element "aop:aspectj-autoproxy" is not bound.