spring boot 启动时运行代码(2)ApplicationListener

本文深入探讨了SpringBoot项目的启动过程,重点分析了StepExecutor组件如何在Spring容器完成bean注入后执行,揭示了其与@PostConstruct注解的区别。通过具体代码示例,展示了StepExecutor在启动时如何调用Spring托管的HelloService bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目概览:

 

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,无法做到。

 

转载于:https://www.cnblogs.com/yaoyuan2/p/10267640.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值