我是AOP的新手,并努力实现以下目标。
我想定义一个注释@RequirePermission,它接受一个参数String或enum,并根据该字符串/ enum我会在建议中做一些计算。因此,应首先验证在具有@RequiredPermissions的Controller中定义的任何方法。到目前为止,这是我的代码。
方面:
package com.myapp.aspect;
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.stereotype.Component;
import com.myapp.security.RequirePermissionType;
import com.myapp.security.RequirePermission;
@Aspect
public class RequirePermissionAspect {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controllerBean() {}
@Pointcut("execution(@com.myapp.security.RequirePermission * com.myapp.controller.*.*(..))")
public void methodPointcut() {}
@Before("controllerBean() && methodPointcut() ")
public void afterMethodInControllerClass(com.myapp.security.RequirePermissionType name) {
System.out.println("before advice..");
System.out.println("before advice.."+name.name());
}
注释:
package com.myapp.security;
public enum RequirePermissionType {
VIEW, MANAGE, IMPORT, SUPER;
}
@Documented
@Target(ElementType.METHOD )
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RequirePermission {
/**
*
* @return
*/
RequirePermissionType name() default RequirePermissionType.VIEW ;
}
现在如果在控制器方法中使用注释,则代码可以正常工作:
@RequestMapping(value={"create"})
@RequirePermission
public String createRegion(Model model){
}
但以下不起作用:
@RequestMapping(value={"create"})
@RequirePermission(name=RequirePermissionType.VIEW)
public String createRegion(Model model){
}
任何人都可以指导我错过的内容以及如何实现这一目标。
答案 0 :(得分:1)
@vamslip这里是更新的方面类。休息所有保持不变。 更新的方面:
package com.myapp.aspect;
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.stereotype.Component;
import com.myapp.security.RequirePermissionType;
import com.myapp.security.RequirePermission;
@Aspect
public class RequirePermissionAspect {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controllerBean() {}
@Pointcut("execution(@com.myapp.security.RequirePermission * com.myapp.controller.*.*(..)) && @annotation(name)")
public void methodPointcut(com.myapp.security.RequirePermission name) {}
@Before("controllerBean() && methodPointcut(name) ")
public void afterMethodInControllerClass(com.myapp.security.RequirePermissionType name) {
System.out.println("before advice..");
System.out.println("before advice.."+name.name());
}
}