Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.
@SpringBootApplication(scanBasePackages= {"cmd","util"}) public class CmdLinerApplication { private static ApplicationContext appCtx; public static void main(String[] args) { appCtx = SpringApplication.run(CmdLinerApplication.class, args); System.out.println("set appCtx after run CmdLinerApplication"); } public static ApplicationContext appCtx() { return appCtx; } } |
@Component public class CmdLineAppString { private String information = "CmdLineAppString:"; public String getInformation() { return information; } public void setInformation(String information) { this.information = information; } public void appendInformation(String apxInfo) { this.information = this.information + ":" + apxInfo; } } |
@Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getAppCtx() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } } |
ApplicationContextAware 获取ApplicationContext
@Component @Order(1) public class CmdLineApp1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { CmdLineAppString apx = SpringContextUtil.getAppCtx().getBean(CmdLineAppString.class); apx.appendInformation("CmdLineApp1 start"); System.out.println(apx.getInformation()); } } |
自动注入的方式获取ApplicationContext
@Component @Order(2) public class CmdLineApp2 implements CommandLineRunner { @Autowired private ApplicationContext appCtx; @Override public void run(String... args) throws Exception { CmdLineAppString apx = appCtx.getBean(CmdLineAppString.class); apx.appendInformation("CmdLineApp2 start"); System.out.println(apx.getInformation()); } } |
执行结果:
CmdLineAppString::CmdLineApp1 start
CmdLineAppString::CmdLineApp1 start:CmdLineApp2 start
set appCtx after run CmdLinerApplication