CommandLineRunner, AppContext初始化后自动执行的程序

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值