zoukankan      html  css  js  c++  java
  • spring boot 启动时运行代码(2)ApplicationListener

    项目概览:

    StepExecutor:

    @Component
    @Slf4j
    public class StepExecutor implements Runnable {
        @Autowired
        private HelloService helloService;
        
        @Override
        public void run() {
            log.info("1111111111111111,helloService={}",helloService);
            try {
                Thread.sleep(1000*10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            helloService.hello();
            log.info("22222222222222222");
        }
    }

    ApplicationStartup

    public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            ApplicationContext ac = event.getApplicationContext();
            StepExecutor stepExecutor = ac.getBean(StepExecutor.class);
            Thread thread = new Thread(stepExecutor);
            thread.start();
        }
    }

    Application

    @SpringBootApplication
    @ComponentScan(basePackages="com.ebc")
    @EnableAutoConfiguration //必须加该注解,否则报:缺少ServletWebServerFactory bean
    @Slf4j
    public class Application {
        public static void main(String[] args) {
            SpringApplication app = new SpringApplication(Application.class);
            app.setBannerMode(Banner.Mode.OFF);
            app.addListeners(new ApplicationStartup());
            app.run(args);
            log.info("PortalApplication is success!");
        }
    }

    HelloService

    @Service
    public class HelloService {
        public void hello() {
           Console.log("xxxxxxxxxxxxxxxxxxxxxx");
        }
    }

    启动:

    16:35:48,920:INFO - Starting ProtocolHandler ["http-nio-9021"]
    16:35:48,921:INFO - 1111111111111111,helloService=com.ebc.service.HelloService@67ed3522
    16:35:48,938:INFO - Using a shared selector for servlet write/read
    16:35:48,961:INFO - Started Application in 3.92 seconds (JVM running for 4.959)
    16:35:48,964:INFO - PortalApplication is success!
    xxxxxxxxxxxxxxxxxxxxxx
    16:35:58,945:INFO - 22222222222222222

    总结:

    等待spring注入了所有bean后才执行执行。意味着,启动时,可以使用spring托管的任意bean。

    而@PostConstract,无法做到。

  • 相关阅读:
    e.printStackTrace()打印在哪里以及如何e.printStackTrace()的内容打印在日志中
    oracle分组并在组内排序
    Java.util.Calendar类
    oracle分页查询
    两个map合并
    【自动化测试】无需图形界面环境下的浏览器开源项目
    【运维工具】logrotate 日志管理神器
    如何查看google chrome 插件源码
    phpexcel 读取数据
    常用开发资源收集
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/10267640.html
Copyright © 2011-2022 走看看