1. 程式人生 > >spring boot 啟動時執行程式碼(2)ApplicationListener

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=[email protected]
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,無法做到。