Spring Boot启动执行

17次阅读

共计 1417 个字符,预计需要花费 4 分钟才能阅读完成。

在一个初春的下午,甲跟我说,要在 Spring Boot 启动服务的时候,设置表结构自增的起始值。于是我用屁股想了一下,不就是在 main 方法里调个方法么。后来实际操作了一把,发现屁股被打了。
于是乎,找到官方文档 (以 2.1.4 为例),找到这一段:

如果你需要在启动 SpringApplication 后执行一些具体的代码,你可以实现 ApplicaitonRunner 或者 CommandLineRunner 接口。两个接口都实现了一个工作方式相同的 run 方法,改方法仅会在 SpringApplication.run(…) 前执行。
唯一不同的是实现 CommandLineRunner 接口的 run 方法参数为 String 类型的数组,而实现 ApplicaitonRunner 的 run 方法的参数则是需要 ApplicationArguments 类型。下面例子供参考。
如果有多个 ApplicaitonRunner 或者 CommandLineRunner 接口的实现存在启动顺序,则可以使用 org.springframework.core.Ordered 接口或者 org.springframework.core.annotation.Order 注解的形式来给他们排序。
由于我没有参数类型等的限制,所以用哪个接口都一样,写个跟官方不一样的,于是代码大概长这样:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
* 服务启动执行项
*/
@Component
public class InstructionStart implements ApplicationRunner {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Value(“${constant.increment}”)
private String increment;

@Autowired
private JdbcTemplate template;

@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
if (increment == null || “”.equals(increment)) {
increment = “0”;
}
logger.info(“ 初始化递增起始值为:{}”, increment);
template.execute(“ALTER TABLE `table` AUTO_INCREMENT = ” + increment);
}
}
深刻的意识到脑子和屁股一样重要。

正文完
 0