依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
AOP通知类
package com.hlxy.mongodb.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAdvice {
@Pointcut("execution(* com.hlxy.mongodb.service..*.*(..))")
public void mongodbAdvice(){}
@Before("mongodbAdvice()")
public void begin(){
System.out.println("前置通知");
}
@After("mongodbAdvice()")
public void after(){
System.out.println("后置通知");
}
@AfterReturning("mongodbAdvice()")
public void AfterReturning(){
System.out.println("最终通知。报异常,就不执行");
}
@AfterThrowing(pointcut = "mongodbAdvice()",throwing="ex")
public void AfterThrowing(Throwable ex){
System.out.println("报异常时执行"+ex.getMessage());
}
@Around("mongodbAdvice()")
public Object allInOne(ProceedingJoinPoint pjp) {
Object result = null;
try {
System.out.println("开启事务------");
result = pjp.proceed();
System.out.println("提交事务------");
} catch (Throwable ex) {
System.out.println("------回滚事务 : " + ex.getMessage());
}finally {
System.out.println("关闭session------");
}
return result;
}
}
springmvc中的拦截器
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("------------------拦截器被访问了--------------------");
HttpSession session = request.getSession();
String userName = (String) session.getAttribute("userName");
String password = (String) session.getAttribute("password");
System.out.println(userName);
System.out.println(password);
if ("dc".equals(userName) && "123456".equals(password)){
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
配置类
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login");
}
}