SpringBoot中利用AOP实现拦截器效果

来源:互联网 发布:哪些网络销售软件好用 编辑:程序博客网 时间:2024/06/06 02:41

既然使用Spring,AOP就是不了或缺的。

尝试好多遍,踩了很多坑,最后总算把效果弄出来了。说起来很简单,只需要建一个类就好了。

@Aspect@Configurationpublic class InfoInterceptor {    private static final String execution_str_01 = "execution(* com.chris.controller.*.*(..))";//controller包下任意方法    private static final String execution_str_02 = "execution(* com.chris.controller..*.*(..))";//controller包或子包下任意方法    private static final String execution_str_03 = "@annotation(org.springframework.web.bind.annotation.RequestMapping)";//带RequestMapping注解的方法    private static final String execution_str_04 = "execution(* com.chris.controller..*(..))";//controller包或子包下任意方法    @Pointcut(execution_str_04)    private void controllerCut() {    }    @Before(value = "controllerCut()")    public void cutBefore(JoinPoint joinPoint) {        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();        HttpServletRequest httpServletRequest = requestAttributes.getRequest();        MsgUtils.show("AOP==>" + httpServletRequest.getRequestURL());        MsgUtils.show("AOP==>" + joinPoint.getSignature());
  }}

效果:



网上查过很多资料,每个人的配置方式都不一样。大致有以下一些,不过最后证实,没有也是可以的:

1.Application类,添加扫描注解:@ComponentScan(basePackages = "com.chris")

2.拦截器使用@Component注解,测试使用@Component或者@Configuration都可以

3.在application.properties中添加spring.aop.auto=true,经测试不加一样可以

4.在pom.xml文件中添加一下节点

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
经测试,不添加一样可以。


测试所浪费的时间,主要还是在execution表达式上。笔者根据网上的资料设计的很多表达式都不成功,目前贴出来的是成功测试过的。还有,就是使用注解判定成功率比较高,个人感觉这样也是比较方便的,自己写一个注解,用起来应该比较灵活。

关于execution表达式,还需要多花点时间去研究。

原创粉丝点击