九、定时任务
@EnableScheduling // 开启定时任务 package com.example.demo.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class HelloTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); // 每3秒执行一次 @Scheduled(fixedRate = 3000) public void echo(){ System.out.println("echo: " + dateFormat.format(new Date())); } }
十、异步任务
@EnableAsync // 开启异步任务 package com.example.demo.task; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class HelloTask { @Async public void sayHello() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }
十一、拦截器
定义拦截器
package com.example.demo.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloInterceptor implements HandlerInterceptor { // 请求处理之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); if("Tom".equals(request.getParameter("key"))){ System.out.println("被拦截"); return false; } else{ System.out.println("放行"); return true; } } // 请求处理之后 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
注册拦截器
package com.example.demo.config; import com.example.demo.interceptor.HelloInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //WebMvcConfigurerAdapter已经被废弃了 @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { // 拦截器按照顺序执行 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HelloInterceptor()).addPathPatterns("/**"); } }