开发中有时候需要实现项目启动后执行相关功能,比如特殊数据初始化处理等。Spring boot提供了CommandLineRunner 来帮我们实现启动时执行一段代码, 示例代码如下:
package com.riskeys.tobtoa;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.riskeys.common.base.constant.CodeConstant;
import com.riskeys.constants.RouteConstants;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.spring.web.SpringfoxWebMvcConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Slf4j
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.riskeys")
@ComponentScan(basePackages = "com.riskeys")
@MapperScan(basePackages = "com.riskeys.**.mapper")
@EnableTransactionManagement
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnClass(SpringfoxWebMvcConfiguration.class)
@SpringBootApplication
public class BizChannel2b2aApplication implements CommandLineRunner{
@Autowired
RabbitTemplate rabbitTemplate;
// @Autowired
// CodeDictService codeDictService;
//系统启动路由刷新开关 0-关闭, 1-开启
@Value("${anyi.route.refresh}")
private String refresh;
public static void main(String[] args) {
SpringApplication.run(BizChannel2b2aApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
// codeDictService.loadCodeDictMetadata();
if(CodeConstant.CODE_YES.equals(refresh)) {
rabbitTemplate.convertAndSend(RouteConstants.ROUTE_REFRESH, "refresh");
}
log.info("BizChannel2b2aApplication start OK");
}
}