Springboot可以在应用启动的时候加载一些初始化数据,通过实现CommandLineRunner接口,其中@Order注解用来定义加载类的顺序。
1:定义两个初始化类 DuckLoad
package com.duck.load;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 启动加载数据
*/
@Component
@Order(value = 1)
public class DuckLoad implements CommandLineRunner{
private static final Logger logger = LoggerFactory.getLogger(DuckLoad.class);
public void run(String... args){
logger.info(this.getClass().getName() + " DuckLoad 方法加载数据");
}
}
DuckLoad2
package com.duck.load;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 启动加载数据
*/
@Component
@Order(value=2)
public class DuckLoad2 implements CommandLineRunner{
private static final Logger logger = LoggerFactory.getLogger(DuckLoad2.class);
public void run(String... args){
logger.info(this.getClass().getName() + " DuckLoad2 方法启动加载数据");
}
}
启动Springboot,可看到在启动的时候就会加载这两个类,顺序也可很清晰的看到,数字小的加载在前