代碼包含在此項目中: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)
注意:使用此方法是最好指定加載順序,並且加載順序的數值留一些間隔,防止以后再添加預加載類。