1. 程式人生 > >【Spring】Springboot監聽器,啟動之後初始化工作

【Spring】Springboot監聽器,啟動之後初始化工作

package com.laplace.laplace.common.starter.config;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/*
* http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
* http://www.baeldung.com/running-setup-logic-on-startup-in-spring
* https://springframework.guru/running-code-on-spring-boot-startup/
*/
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent>{
private static final Logger LOG = LoggerFactory.getLogger(ApplicationStartup.class);

@Autowired
private GrpcLocalProxyService grpcLocalProxyService;

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (grpcLocalProxyService == null) {
LOG.info("grpcLocalProxyService is null/disabled, no need to loadProtoResources");
}
try {
grpcLocalProxyService.loadProtoResources();
} catch (IOException | ClassNotFoundException e) {
LOG.error("grpcLocalProxyService loadProtoResources exception, {}", e);
}
}

}

package com.laplace.laplace.common.starter.config;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/*
 * http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
 * http://www.baeldung.com/running-setup-logic-on-startup-in-spring
 * https://springframework.guru/running-code-on-spring-boot-startup/
*/    
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent>{
    private static final Logger LOG = LoggerFactory.getLogger(ApplicationStartup.class);
    
    @Autowired
    private GrpcLocalProxyService grpcLocalProxyService;
    

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (grpcLocalProxyService == null) {
            LOG.info("grpcLocalProxyService is null/disabled, no need to loadProtoResources");
        } 
        try {
            grpcLocalProxyService.loadProtoResources();
        } catch (IOException | ClassNotFoundException e) {
            LOG.error("grpcLocalProxyService loadProtoResources exception, {}", e);
        }
    }
    
}