代码包含在此项目中:https://gitee.com/zhangjunqing/spring-boot/tree/master/springboot-sample
1 通过实现commandlinerunner接口,可以在spring加载完进行一些数据的预处理操作。在实现此方法时最好加上@Order注解来指定预加载的顺序。
添加两个类实现commandlinerunner接口,并指定他们的加载顺序,同时在加载后获取spring 容器中的bean并修改。
1.1 辅助类,放在spring容器当中,可以在预加载程序中注入此类的对象,并且修改其值
package com.springboot.service; import org.springframework.stereotype.Service; /** * 程序测试辅助类 制定年龄为10 * @author 76524 * */ @Service public class ModelTest { private int age = 10; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1.2 加载顺序为20的预加载类,并且修改辅助对象的年龄,将其增加1
package com.springboot.commandrunner; import javax.annotation.Resource; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import com.springboot.service.ModelTest; @Component @Order(20) //启动时的加载顺序,越小越提前加载 public class StartRunner1 implements CommandLineRunner { @Resource private ModelTest modeTest; public void run(String... arg0) throws Exception { System.out.println("启动预加载1 " + modeTest.getAge()); modeTest.setAge(modeTest.getAge()+1); //增加1 } }
1.3 加载顺序为40的预加载类,打印新的辅助对象的年龄
package com.springboot.commandrunner; import javax.annotation.Resource; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import com.springboot.service.ModelTest; @Component @Order(40) //启动时的加载顺序,越小越提前加载 public class StartRunner2 implements CommandLineRunner{ @Resource private ModelTest modeTest; public void run(String... arg0) throws Exception { System.out.println("启动预加载2 " + modeTest.getAge()); } }
1.4 结果如下
2017-10-15 15:32:39.205 INFO 17044 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
启动预加载1 10
启动预加载2 11
2017-10-15 15:32:39.215 INFO 17044 --- [ main] com.springboot.App : Started App in 4.901 seconds (JVM running for 5.608)
注意:使用此方法是最好指定加载顺序,并且加载顺序的数值留一些间隔,防止以后再添加预加载类。