一般情况下,我们的项目在刚启动的时候就需要初始化一些数据,特别有些是需要查询表的情况下,这时候我们就要用到springboot的初始化了,
我们需要实现 CommandLineRunner 接口并在类上面添加 @Component 和 @Order(2) 注解 , 并重写run()方法,springboot会自动扫描这些注解,即可完成初始化,
注意:这个初始化是在springboot加载完了所有bean之后执行的初始化方法,所以我们可以直接使用 @AutoWired 注解进行依赖注入 ,是不是很方便呢?
代码如下:
package com.love.app.filter;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.love.app.common.CommonConstants;
import com.maven.common.mapper.SystemParamMapper;
import com.maven.common.model.SystemParam;
import com.xd.base.common.utils.StringUtils;
/**
*
* <spring boot初始化>
*
* @version 1.0
* @author 2018年8月5日 下午1:48:44
*/
@Component
@Order(2) // 通过order值的大小来决定启动的顺序
public class InitSpringBoot implements CommandLineRunner {
private Logger log = LoggerFactory.getLogger(InitSpringBoot.class);
@Autowired
private SystemParamMapper systemParamMapper;
@Override
public void run(String... args) throws Exception {
try {
systemParamMapper.init();
log.info("springboot初始化完成");
} catch (Exception e) {
log.error("springboot初始化异常", e);
}
}
}