Aop基于注解拦截 和 基于方法拦截
引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
基于注解拦截
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name();
}
@Service
public class AnnotationService {
@Action(name = "注解式拦截add操作,我是注解的name值")
public void add() {
System.out.println("AnnotationService的添加方法被调用了");
}
}
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.xin.demoxin.aop.Action)")
public void annotationPointCut() {
}
@After("annotationPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("\n注解是拦截器的方法是:" + method.getName());
Action action = method.getAnnotation(Action.class);
System.out.println("方法上注解的文字是:" + action.name());
}
}
@Configuration
@ComponentScan("com.xin.demoxin.aop")
@EnableAspectJAutoProxy
public class AopConfig {
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AopConfig.class);
AnnotationService bean = context.getBean(AnnotationService.class);
bean.add();
}
AnnotationService的添加方法被调用了 //先调用具体的方法
注解是拦截器的方法是:add //然后走 切面的方法
方法上注解的文字是:注解式拦截add操作,我是注解的name值
基于方法的拦截
@Service
public class MethodService {
public void add() {
System.out.println("MethodService的添加方法被调用了");
}
}
@Before("execution(* com.xin.demoxin.aop.MethodService.*(..))")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("MethodService里将要被调用的方法是:" + method.getName());
}
MethodService bean2 = context.getBean(MethodService.class);
bean2.add();
MethodService里将要被调用的方法是:add
MethodService的添加方法被调用了
拦截器 Interceptor
统计 请求时长的拦截器
public class DemoInterceptor implements AsyncHandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long time = System.currentTimeMillis();
request.setAttribute("startTime", time);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long startTime = (Long) request.getAttribute("startTime");
request.removeAttribute("startTime");
long endTime = System.currentTimeMillis();
System.out.println("本次请求的时间ms是:" + (endTime - startTime));
request.setAttribute("handlingTime", endTime - startTime);
}
}
MVC配置
@Configuration
@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public DemoInterceptor demoInterceptor() {
return new DemoInterceptor();
}
@Resource
private DemoInterceptor demoInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(demoInterceptor);
}
}
@RestController
public class TestController2 {
@GetMapping("/testOne")
public String testOne() {
try {
Thread.sleep(1000L);
} catch (Exception e) {
}
return "haha";
}
}
本次请求的时间ms是:1002
ControllerAdvice
@ControllerAdvice
@ExceptionHandler
@InitBinder
@ModelAttribute
编写:控制器建言
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg", "额外信息");
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("id");
}
@ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception e, WebRequest request) {
ModelAndView m = new ModelAndView("error");
m.addObject("errorMessage", e.getMessage());
return m;
}
}
@GetMapping("/testOne2")
public String testOne2(@ModelAttribute("msg") String msg) {
System.out.println("请求到了");
throw new IllegalArgumentException("非常抱歉,参数异常。" + msg);
}
以前写的一个
@ResponseBody
@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
public ResponseEntity<Pesponsibles> methodArgumentNotValidExceptionHandler(Exception e, BindingResult bindingResult) {
Pesponsibles p = new Pesponsibles();
if (bindingResult.hasErrors()) {
} else {
p.setDefaultMessage(e.getMessage());
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
p.setField("bindingResult错误字段");
if (bindingResult.hasErrors()) {
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
StringBuilder message = new StringBuilder("提示:");
fieldErrors.forEach(i -> message.append(i.getDefaultMessage()).append("!"));
p.setDefaultMessage(message.toString());
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
过滤器
过滤器代码
public class LogCostFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("测试");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("Execute cost=" + (System.currentTimeMillis() - start));
}
@Override
public void destroy() {
}
}
配置类
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogCostFilter());
registration.addUrlPatterns("/*");
registration.setName("LogCostFilter");
registration.setOrder(1);
return registration;
}
}
|