在一个初春的下午,甲跟我说,要在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;/** * 服务启动执行项 */@Componentpublic 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); }}深刻的意识到脑子和屁股一样重要。