关于Aspect类。
@Aspect
@Component
public class PostAop{
@Around("execution(* com.blog.controllers.PostController.add(..)) && args(request,..)")
public String Authorized(ProceedingJoinPoint jp, HttpServletRequest request) throws Throwable {
还有注释类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) // can use in method only.
public @interface Authorized {
public boolean Admin() default true;
public boolean Writer() default false;
}
最后这是我的aspect配置类。
@Configuration
@ComponentScan(basePackages = { "com.blog" })
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AspectConfig {
@Bean
public PostAop postAop(){
return new PostAop();
}
}
这是PostController类
@Controller
@RequestMapping(value = {"","/post"})
public class PostController {
...
@GetMapping("/add")
@Authorized(Writer = true)
public String add(ModelMap model,Article article,HttpSession session) {
model.addAttribute("tags", tagService.getAllTags());
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("post", post);
return "post/add";
}
我其实不知道问题出在哪里,我在运行应用程序时没有收到任何异常,但是我的方面类PostAop从来没有被调用。我是不是在配置中遗漏了什么?
切点表达式
@Around("execution(* com.blog.controllers.PostController.add(..)) && args(request,..)")
可以解释为 ,建议一个符合以下条件的连接点(在Spring AOP的情况下,方法执行)。
执行方法 com.blog.controllers.PostController.add
的任何返回类型(*)和任何参数(...)。
和
该方法应该有 HttpServletRequest request
作为其第一个参数
现在在你的 PostController
该方法 add(ModelMap model,Article article,HttpSession session)
将不符合点切割表达式
如果你去掉了 args(request,..)
你可以按以下方式访问HttpServletRequest。
@Around("execution(* com.blog.controllers.PostController.add(..)) && within(com.blog.controllers..*)")
public String authorized(ProceedingJoinPoint jp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
return (String) jp.proceed();
}
within()
是一个范围代号,用于缩小类的范围,以便提出建议。
注释 。
当您对 Aspect
类与 @Component
,它将会被自动检测出来。@ComponentScan(basePackages = { "com.blog" })
如果 PostAop
被放置在根包下的任何级别 com.blog
. 这意味着你不需要使用工厂方法和 @Bean
注释。其中任何一个 @Component
或 @Bean
是必须的。
根据java的命名惯例,该方法的名称将是 authroized()
而不是 Authorized()
希望对你有所帮助。