SpringBoot拦截器和AOP

SpringBoot AOP编程

  引入环境:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

额外功能类开发:

@Aspect
@Configuration
public class TestAOP{
@Before("execution(* com.com.service..*.*(..))")
public void before(JoinPoint joinPoint) throws Throwable {
// 需要添加的额外功能
System.out.println("------- this is before --------");
}
@After("execution(* com.com.service..*.*(..))")
public void after(JoinPoint joinPoint){
System.out.println("------- this is after --------");
}
@Around("execution(* com.com.service..*.*(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint){
try {
System.out.println("------- this is around before --------");
Object proceed = proceedingJoinPoint.proceed();
System.out.println("------- this is around after --------");
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
}
}
}

SpringBoot拦截器开发:

拦截器类:

public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o) throws Exception {
System.out.println("==拦截器==");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}

2.拦截器配置


@Configuration
public class TestConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
TestInterceptor interceptor = new TestInterceptor();
registry.addInterceptor(interceptor)
.addPathPatterns("/test/**")
.excludePathPatterns("/test/test1");
}
}

猜你喜欢

转载自blog.csdn.net/flyrobot/article/details/88042895
今日推荐