Official account: Java Xiaokaxiu, website: Javaxks.com

Author: FOEVERYANG. Source: www.cnblogs.com/lsgspace/p/…

I. Opening name

In springBoot we sometimes need to preload data or execute a method when a project starts up. What are the ways to preload data? I’m going to take you through them one by one

1. Implement the ServletContextAware interface and rewrite its setServletContext method

@Component Public class TestStarted implements ServletContextAware {/** * is called after the normal bean property is populated but before initialization Callback similar to afterPropertiesSet of initializingBean or custom init method * */ @override public void setServletContext(ServletContext) ServletContext) {system.out.println ("setServletContext method "); }}Copy the code

Note: This method is executed after the properties of the normal Bean are populated, but before the Bean is initialized

2. Implement the ServletContextListener interface

/** * All servletContextListener contexts are notified of initialization before any filter or servlet in the Web application is initialized. */ @Override public void contextInitialized(ServletContextEvent sce) { //ServletContext servletContext = sce.getServletContext(); System.out.println(" Execute contextInitialized method "); }Copy the code

3. Place a Spring container scan (@Component) on the class of the method to be executed and add @postConstruct annotations or static code blocks to the method to be executed

@component public class Test2 {// Static code blocks are automatically executed after dependency injection and take priority over static{system.out.println ("-- --static--"); @postConstruct public static void haha(){/** * @postconstruct public static void haha(){ System.out.println(" @postContruct 'automatically called after dependency injection "); }}Copy the code

4. Implement ApplicationRunner interface

/** * indicates the interface that should run when the bean is included in the SpringApplication. Multiple ApplicationRunner beans * can be defined in the same application context, which can be sorted using an ordered interface or an @Order annotation. */ @Override public void run(ApplicationArguments args) throws Exception { System.out.println("ApplicationRunner run method "); }Copy the code

4. Implement the CommandLineRunner interface

/** * indicates the interface that should run when the bean is included in the SpringApplication. Multiple CommandLinerunner Beans can be defined in the same application context and can be ordered using an ordered interface or an @Order annotation. * If you need access to applicationArguments instead of raw string arrays, consider using ApplicationRunner. * */ @Override public void run(String... ) Throws Exception {system.out. println("CommandLineRunner's Run method "); }Copy the code