在spring或者springboot项目中,经常会有这样的需求,就是项目启动之后,会执行一段代码,做一些初始化的操作,执行完毕,就不再重复执行。
import javax.servlet.ServletContextListener;
@Component
public class DemoServiceWithServletContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("1: run with ServletContextListener , method -> contextInitialized().");
}
import org.springframework.beans.factory.InitializingBean;
@Component
public class DemoServiceWithInitializingBean implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("2: run with InitializingBean , method -> afterPropertiesSet().");
}
import javax.annotation.PostConstruct;
@Component
public class DemoServiceWithPostConstruct {
@PostConstruct
public void run() {
System.out.println("3: run with PostConstruct , method -> run().");
}
import org.springframework.web.context.ServletContextAware;
@Component
public class DemoServiceWithServletContextAware implements ServletContextAware{
@Override
public void setServletContext(ServletContext servletContext) {
System.out.println("4: run with ServletContextAware , method -> setServletContext().");
}
import org.springframework.boot.ApplicationRunner;
@Component
public class DemoServiceWithApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("5: run with ApplicationRunner , method -> run().");
}
import org.springframework.boot.CommandLineRunner;
@Component
public class DemoServiceWithCommandLineRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("6: run with CommandLineRunner , method -> run().");
}
@Component
public class SpringStartListener implements ApplicationListener {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
}
}