Java 方面在我的spring项目中不起作用
关于方面类:Java 方面在我的spring项目中不起作用,java,spring-data,spring-aop,Java,Spring Data,Spring Aop,关于方面类: @Aspect @Component public class PostAop{ @Around("execution(* com.blog.controllers.PostController.add(..)) && args(request,..)") public String Authorized(ProceedingJoinPoint jp, HttpServletRequest request) throws Throwable {
@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;
}
@Configuration
@ComponentScan(basePackages = { "com.blog" })
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AspectConfig {
@Bean
public PostAop postAop(){
return new PostAop();
}
}
最后,这是我的方面配置类:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) // can use in method only.
public @interface Authorized {
public boolean Admin() default true;
public boolean Writer() default false;
}
@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,..)")
可以解释为,通知一个符合以下条件的连接点(SpringAOP中的方法执行)
执行任何返回类型(*)和任何参数(..)的方法com.blog.controllers.PostController.add
及
该方法的第一个参数应该是HttpServletRequest
现在,在PostController
中,方法add(ModelMap模型、文章、HttpSession会话)
将与切入点表达式不匹配
@Around("execution(* com.blog.controllers.PostController.add(..)) && args(request,..)")
如果删除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()
是一个范围指示符,用于将类的范围缩小为建议
注:
当您使用@Component
注释方面
类时,如果PostAop
放在根包com.blog
下的任何级别,则@ComponentScan(basePackages={“com.blog”})将自动检测到它。这意味着您不必使用工厂方法和@bean
注释来创建bean。需要@Component
或@Bean
中的一个
根据java命名约定,方法的名称将是authroyed()
而不是Authorized()
希望这能有所帮助。请分享控制器类代码,该代码应该被告知。@R.G我在上面的主要帖子中添加了它