介绍
使用springboot手动执行一些逻辑的情况下,单次运行类似脚本的程序。
pom.xml
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32<?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
复制代码
1
2
3
4
5
6
7@Service public class StatService { public void doSomething() { System.out.println("===================: this is a test service but nothing"); } }
Controller
复制代码
1
2
3
4
5
6
7
8
9
10
11
12@Component public class StatTask { private StatService statService; @Autowired public StatTask(StatService statService) { this.statService = statService; } public void doSomething() { statService.doSomething(); } }
springboot启动类
复制代码
1
2
3
4
5
6
7
8
9
10@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就是一个“脚本”程序。
如果想启动程序后多次调用该方法,如下配置
controller
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14@Component public class StatTask { private StatService statService; @Autowired public StatTask(StatService statService) { this.statService = statService; } @Scheduled(fixedRate = 5000L) // --------------这里----------------- public void doSomething() { statService.doSomething(); } }
springboot启动类
复制代码
1
2
3
4
5
6
7
8
9
10
11@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”,且进程永驻。
最后
以上就是活力跳跳糖最近收集整理的关于springboot执行单次程序的全部内容,更多相关springboot执行单次程序内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复