Visual Studio 中的 Agent Skill:让 Copilot 适配团队工作模式
2026/6/26 1:11:46
Spring框架提供了强大的定时任务支持。通过使用
@Scheduled注解,可以将一个方法标记为定时任务,并指定任务的执行时间规则。可以设置任务在固定的时间点执行,也可以设置任务在一定的时间间隔内重复执行。Spring的定时任务功能更加灵活,支持各种时间表达式,也可以配置多线程执行任务。
@ScheduledStaticScheduleTask类cron= [秒] [分] [小时] [日] [月] [周] [年]@Configuration// 1.配置类@EnableScheduling// 2.开启定时任务publicclassStaticScheduleTask{// 3.添加定时任务 每5秒执行一次@Scheduled(cron="0/5 * * * * ?")publicvoidconfigureTasks(){System.out.println("执行静态定时任务"+Thread.currentThread().getName());}}输出结果: 执行静态定时任务scheduling-1执行静态定时任务scheduling-1执行静态定时任务scheduling-1@Configuration // 1.配置类 @EnableScheduling // 2.开启定时任务 @EnableAsync // 开启多线程 public class StaticScheduleTask { // 3.添加定时任务 每5秒执行一次 @Scheduled(cron = "0/5 * * * * ?") @Async// 多线程执行 异步 public void configureTasks(){ System.out.println("执行静态定时任务"+Thread.currentThread().getName()); } } 输出结果: 执行静态定时任务task-1 执行静态定时任务task-2 执行静态定时任务task-3SpringMvc的处理拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理,开发可以自己定义一些拦截器来实现特定功能。
过滤器
servlet规范中的一部分,任何java web程序都可以使用。
在url-pattern中配置之后,可以对所要访问的资源进行拦截
拦截器拦截器
SpringMvc框架自己的,只有使用了SpringMvc框架工程才能使用。js,css,image…是不会进行拦截的Handlerlnterceptor接口@ComponentpublicclassLoginInterceptorimplementsHandlerInterceptor{//preHandle是请求执行前执行的@OverridepublicbooleanpreHandle(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto)throwsException{System.out.println("进入拦截器");returntrue;}//postHandler是请求结束执行的 当preHandle返回true才会执行publicvoidpostHandle(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto,ModelAndViewmodelAndView){System.out.println("请求结束执行");}//afterCompletion是视图渲染完成后才执行的publicvoidafterCompletion(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto,Exceptione)throwsException{System.out.println("视图渲染完成后执行");}}2.2.2实现WebMvcConfigurer接口配置拦截路径
三种方式
WebMvcConfigurerAdapter(spring5.0 以弃用,不推荐)WebMvcConfigurer(推荐)WebMvcConfigurationSupport会导致SpringBoot自动配置失效实现WebMvcConfigurer
addlnterceptor:需要一个实现Handlerlnterceptor接口的拦截器实例
addPathPaterns:用于设置拦截器的过滤路径规则
addPathPatterns(“/**”)对所有请求都拦截
excludePathPatterns:用于设置不需要拦截的过滤规则拦截器主要用途:进行用户登录状态的拦截,日志的拦截等
@ConfigurationpublicclassWebJavaBeanConfigurationimplementsWebMvcConfigurer{@AutowiredprivateLoginInterceptorloginInterceptor;publicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login").excludePathPatterns("/user/logout");}}