使用场景:在spring或者springboot项目中,经常会有这样的需求,就是项目启动之后,会执行一段代码,做一些初始化的操作,执行完毕,就不再重复执行。
1、Spring项目或者SpringBoot项目,实现InitializingBean接口
@Slf4j
@Component
public class DemoServiceWithInitializingBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
log.info("2: run with InitializingBean");
}
}
2、SpringBoot项目,实现 ApplicationRunner 或者 CommandLineRunner
实现ApplicationRunner接口
@Slf4j
@Component
public class DemoServiceWithApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("5: run with ApplicationRunner ");
}
}
实现CommandLineRunner接口
@Slf4j
@Component
public class DemoServiceWithCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("6: run with CommandLineRunner ");
}
}
3、Spring web项目,ServletContextListener 或者 ServletContextAware
实现ServletContextAware接口
@Slf4j
@Component
public class DemoServiceWithServletContextAware implements ServletContextAware {
@Override
public void setServletContext(ServletContext servletContext) {
log.info("4: run with ServletContextAware ");
}
}
实现ServletContextListener接口
@Slf4j
@Component
public class DemoServiceWithServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("1: run with ServletContextListener");
}
}
4、使用@PostConstruct注解
@Slf4j
@Component
public class DemoServiceWithPostConstruct {
@PostConstruct
public void run() {
log.info("3: run with PostConstruct");
}
}
5、测试
@SpringBootApplication
public class App {
public static void main( String[] args ){
SpringApplication.run(App.class, args);
}
}