我的春季项目无法正常工作

时间:2020-05-03 02:36:50

标签: java spring-data spring-aop

关于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;

}

最后这是我的方面配置类:

@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从未被调用。我是否错过了配置中的某些内容?

1 个答案:

答案 0 :(得分:1)

切入点表达式

@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" })放在根包{{1}下的任何级别,PostAop将会自动检测到它。 }}。这意味着您不必使用工厂方法和com.blog注释来创建bean。 @Bean@Component之一。

根据Java命名约定,方法的名称为@Bean,而不是authroized()

希望这会有所帮助。