spring-boot 如何实现单次执行程序

目录
  • spring-boot 单次执行程序
    • pom.xml
    • Service类
    • 执行逻辑入口类
    • Spring-boot 启动类
    • 执行逻辑入口类
    • Spring-boot 启动类
  • 启动时执行单次任务
    • @EnableScheduling注解就可以实现定时去执行任务了
    • @ServletComponentScan注解

spring-boot 单次执行程序

spring-boot做为spring的集大成框架,大部分时候作为WEB服务被集成使用,但某些情况下,需要手动执行一些逻辑的情况下,单次运行的类似脚本的程序也是很有用的。

本文记录一下使用spring-boot作为单次可执行程序配置方式。

pom.xml

注意:pom.xml部分只需引入spring-boot-starter模块,尤其不要引入web模块,其他非spring本身模块可以随意引入

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <!-- 按工程习惯处理parent部分 -->
    </parent>
    <groupId>com.leon</groupId>
    <artifactId>sprint-boot-task</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

主要代码结构

Service类

@Service
public class StatService {
    public void doSomething() {
        System.out.println("===================: this is a test service but nothing");
    }
}

执行逻辑入口类

@Component
public class StatTask {
    private StatService statService;
    @Autowired
    public StatTask(StatService statService) {
        this.statService = statService;
    }
    public void doSomething() {
        statService.doSomething();
    }
}

Spring-boot 启动类

@SpringBootApplication
public class TaskApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TaskApplication.class, args);
        StatTask statTask = context.getBean(StatTask.class);  // 获取逻辑入口类的实例
        statTask.doSomething();
    }
}

如此这般后,启动这个springboot工程,执行完启动类中的调用过程后,程序就会自动退出。

基本上,不配置启用spring mvc和定时Job,这种配置下的springboot就是一个“脚本”程序。

这里举个?,上面的代码加上两个注解,就会变成常驻进程程序:

执行逻辑入口类

@Component
public class StatTask {
    private StatService statService;
    @Autowired
    public StatTask(StatService statService) {
        this.statService = statService;
    }

 @Scheduled(fixedRate = 5000L)   // --------------这里-----------------
    public void doSomething() {
        statService.doSomething();
    }
}

Spring-boot 启动类

@SpringBootApplication
@EnableScheduling   // --------------这里---------------
public class TaskApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TaskApplication.class, args);
        StatTask statTask = context.getBean(StatTask.class);
        statTask.doSomething();
    }
}

与最上面区别的是,上面只执行一次,输出 “this is a test service but nothing” 就完事了,进程自动退出,

加上两个注解后就会每5秒输出一次 “this is a test service but nothing”,且进程永驻。

当然这种情况下使用脚本语言如python、nodeJs等可能更好一些,但在其他语言不熟的情况下,使用spring-boot来应急也是极好的。

启动时执行单次任务

最近做任务遇到一个问题,需要在项目启动时候执行扫描数据库表的任务,用于异常恢复容灾,一开始想的是可不可以使用定时任务

代码如下 并且在启动类加上

@EnableScheduling注解就可以实现定时去执行任务了

package com.beihui.service.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class XXXTask {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Scheduled(cron = "0 0 0 * * ?")
    public void bTask() {
        long startCurrentTime = System.currentTimeMillis();
        logger.info("开始执行定时任务:" + startCurrentTime);
        //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    } 

    @Scheduled(cron = "0 */1 * * * ?")
    public void runUpdateDbTask() {
        long startCurrentTime = System.currentTimeMillis();
        logger.info("开始执行更新数据库剩余次数定时任务:" + startCurrentTime);
       //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    }

    @Scheduled(fixedDelay = 60 * 1000 * 10)
    public void cTask() {
        long startCurrentTime = System.currentTimeMillis();
       //业务处理

        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    }
}

但是这个并不能单次执行任务,所以后来 使用listener

代码如下,并在启动类加上

@ServletComponentScan注解

package xx.xx.xx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class XXXListener implements ServletContextListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass()); 

//项目启动执行
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        long startTime = System.currentTimeMillis();
        logger.info("开始执行启动任务,{}"+startTime);
        //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("执行启动任务结束,共花费时间{}"+(startTime-endTime));
    }

//项目终止时执行
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Boot 项目启动自动执行方法的两种实现方式

    目录 实际应用场景: 第一种实现ApplicationRunner接口 第二种实现CommandLineRunner接口 对比: 注意: 实际应用场景: springboot项目启动成功后执行一段代码,如系统常量,配置.代码集等等初始化操作:执行多个方法时,执行顺序使用Order注解或Order接口来控制. Springboot给我们提供了两种方式 第一种实现ApplicationRunner接口 package org.mundo.demo.core; import org.springfra

  • 详解Spring Boot 项目启动时执行特定方法

    Springboot给我们提供了两种"开机启动"某些方法的方式:ApplicationRunner和CommandLineRunner. 这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法.我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的. CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用App

  • 详解如何在Spring Boot启动后执行指定代码

    在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据等等. 在Spring中可以通过ApplicationListener来实现相关的功能,不过在配合Spring Boot使用时就稍微有些区别了. 创建ApplicationListener 这里以填充部分测试数据为例子,首先实现ApplicationStartup类. publicclass ApplicationStartup implements ApplicationListener<ContextRefr

  • spring boot在启动项目之后执行的实现方法

    前言 我们在web项目启动之后有时候还会做点其它的东西(比如,导入数据脚本),下面就说说spring-boot里怎么在程序启动后加入自己要执行的东西 方法如下: 新建一个类:BeforeStartup.java @Configuration public class BeforeStartup implements ApplicationListener<ContextRefreshedEvent> { @Autowired private InitDB initDB; @Override p

  • 详解spring boot容器加载完后执行特定操作

    有时候我们需要在spring boot容器启动并加载完后,开一些线程或者一些程序来干某些事情.这时候我们需要配置ContextRefreshedEvent事件来实现我们要做的事情 1.ApplicationStartup类 public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent>{ public void onApplicationEvent(ContextRefreshedEve

  • Maven 多模块父子工程的实现(含Spring Boot示例)

    一.为什么要用Maven多模块 假设有这样一个项目,很常见的Java Web应用.在这个应用中,我们分了几层: Dao Service Web 对应的,在一个项目中,我们会看到一些包名: org.xx.app.dao org.xx.app.service org.xx.app.web org.xx.app.util 但随着项目的进行,你可能会遇到如下问题: 这个应用可能需要有一个前台和一个后台管理端,你发现大部分dao,一些service,和大部分util是在两个应用中可. pom.xml中的依

  • Spring Boot学习入门之表单验证

    前言 所谓表单验证,即校验用户提交的数据的合理性的,比如是否为空了,密码长度是否大于6位,是否是纯数字的,等等.spring boot是如何帮我们实现表单验证的呢?下面话不多说了,来一起看看详细的介绍吧. 假设现在我们存在这么一个注册界面: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>hello spring boot</title>

  • Spring Boot 表单验证篇

    一. spring-boot-starter-validation 依赖概述 上一篇 <Spring Boot Web 开发注解篇>,就可以快速地进行 Web 开发.那么在表单提交的时候,我们需要进行验证.前端验证可以挡住 99% 的小白用户,这里要实现服务端验证. Starters 机制告诉我们,只要加入 spring-boot-starter-validation 这个 Starter ,就可以使用其实现验证.那什么是 spring-boot-starter-validation? spr

  • Spring Boot与Kotlin处理Web表单提交的方法

    我们在做web开发的时候,肯定逃不过表单提交,这篇文章通过Spring Boot使用Kotlin 语言 创建和提交一个表单. 下面我们在之前<Spring Boot 与 Kotlin使用Freemarker模板引擎渲染web视图>项目的基础上,增加处理表单提交. build.gradle 文件没有变化,这里贴一下完整的build.gradle group 'name.quanke.kotlin' version '1.0-SNAPSHOT' buildscript { ext.kotlin_v

  • spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)

    创建项目 使用IDEA创建一个spring-boot项目,依赖选上 web, validation, freemarker 即可 先看看效果 创建实体类 创建并加上注解,代码如下 public class Person implements Serializable { @NotNull @Length(min = 3, max = 10) // username长度在3-10之间 private String username; @NotNull @Min(18) // 年龄最小要18岁 pr

  • Spring Boot 2 Thymeleaf服务器端表单验证实现详解

    这篇文章主要介绍了Spring Boot 2 Thymeleaf服务器端表单验证实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 表单验证分为前端验证和服务器端验证. 服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范. 项目依赖加入spring-boot-starter-thymeleaf时,默认就会加入Hibernate Validator的依赖. 开

  • spring-boot 如何实现单次执行程序

    目录 spring-boot 单次执行程序 pom.xml Service类 执行逻辑入口类 Spring-boot 启动类 执行逻辑入口类 Spring-boot 启动类 启动时执行单次任务 @EnableScheduling注解就可以实现定时去执行任务了 @ServletComponentScan注解 spring-boot 单次执行程序 spring-boot做为spring的集大成框架,大部分时候作为WEB服务被集成使用,但某些情况下,需要手动执行一些逻辑的情况下,单次运行的类似脚本的程

  • 教你在Spring Boot微服务中集成gRPC通讯的方法

    一.首先声明gRPC接口 这里引入的是最新的gRpc-core 1.37版本, 采用的grcp-spring-boot-starter封装的版本进行实现,github地址: https://github.com/yidongnan/grpc-spring-boot-starter 要实现gRpc通讯, 先定义接口以及入参出参信息 syntax = "proto3"; option java_multiple_files = true; option java_package = &qu

  • docker连接spring boot和mysql容器方法介绍

    在之前使用docker部署运行了Spring Boot的小例子,但是没有使用数据库.在这一篇中,介绍docker如何启动mysql容器,以及如何将Spring Boot容器与mysql容器连接起来运行. docker基本命令 首先熟悉一下在操作过程中常用的docker基本命令: docker images:列出所有docker镜像 docker ps:列出所有运行中的容器,-a参数可以列出所有容器,包括停止的 docker stop container_id:停止容器 docker start

  • 使用Spring boot + jQuery上传文件(kotlin)功能实例详解

    文件上传也是常见的功能,趁着周末,用Spring boot来实现一遍. 前端部分 前端使用jQuery,这部分并不复杂,jQuery可以读取表单内的文件,这里可以通过formdata对象来组装键值对,formdata这种方式发送表单数据更为灵活.你可以使用它来组织任意的内容,比如使用 formData.append("test1","hello world"); 在kotlin后端就可以使用@RequestParam("test1") greet

随机推荐