资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

springBoot启动时怎么选择可执行的任务

本篇文章给大家分享的是有关springBoot启动时怎么选择可执行的任务,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

创新互联公司凭借专业的设计团队扎实的技术支持、优质高效的服务意识和丰厚的资源优势,提供专业的网站策划、网站设计、网站建设、网站优化、软件开发、网站改版等服务,在成都十载的网站建设设计经验,为成都上千余家中小型企业策划设计了网站。

CommandLineRunner

看源码说明为:

Spring Batch jobs. Runs all  jobs in the surrounding context by default. Can also be used to launch a specific job
  by providing a jobName。

即,在spring容器启动的时候就开始批处理一些任务。是随spring启动而加载运行的。

使用方式:自定义一个model 实现该及接口并重写run 方法

package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
}

}

===========如果有多个类实现CommandLineRunner接口,如何保证顺序??? @Order注解 来实现

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行 2222 <<<<<<<<<<<<<");
}

}
```
```
package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=1)
public class MyStartupRunner2 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行 111111 <<<<<<<<<<<<<");
}

}
```
> 控制台显示
```
>>>>>>>>>>>>>>>服务启动执行 11111111 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服务启动执行 22222222## 标题 ## <<<<<<<<<<<<<
```
> 根据控制台结果可判断,@Order 注解的执行优先级是按value值从小到大顺序。

改接口常用语 boot 启动初始化时 加载一些配置常量。比如一些三方的访问接口配置常量。

例如:

package com.big.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;


import lombok.Getter;
@Component
@Getter
public class RiskConstants  implements CommandLineRunner{
	@Autowired
	private Environment env;
	/**常数项配置*/
	public static final String TD_URL_DOMAIN = "";
	
	
	

	@Override
	public void run(String... args) throws Exception {
		RiskConstants.TD_URL_DOMAIN = env.getProperty("t.url.domain");


		System.out.println("===============配置文件  config加载完成-------------------------");
	}
}

以上就是springBoot启动时怎么选择可执行的任务,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


网页名称:springBoot启动时怎么选择可执行的任务
网页网址:http://cdkjz.cn/article/gpdjsc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220