本文概览:介绍了spring boot常用功能,如@Scheduled和@EnableScheduling来实现定时任务、自定义拦截器等。
准备
新建spring boot项目
1 @Schedule
介绍了spring boot通过@Scheduled和@EnableScheduling来实现定时任务、
1、新增一个@EnableScheduling
1 2 3 4 5 6 7 8 |
@SpringBootApplication(scanBasePackages = {"comtemplate.springboottemplate"}) @ServletComponentScan @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
2、在函数上新增@Scheduled,如下是每5秒执行一次
1 2 3 4 5 |
@Scheduled(cron="*/5 * * * * ?") public void test(){ LOGGER.info("test---"); } } |
2 拦截器
有一个需要改变modeMap值的需求,此时可以定义后置拦截器,如下
1 2 3 4 5 6 7 8 9 |
public class ChangeModelMapInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 自定义操作modelAndView的逻辑 } } |
加载拦截器
1 2 3 4 5 6 7 8 |
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new ChangeModelMapInterceptor()); } } |
参考:https://www.baeldung.com/spring-model-parameters-with-handler-interceptor
3 设定首页
设定首页
1 2 3 4 5 6 7 8 9 10 11 |
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/homepage"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); } } |