After the spring container is loaded, execute your own method
During the development process, I encountered a service that I wanted to automatically start after the project started. Since I used spring, I used spring's listener, which has the onApplicationEvent() method. After the Spring container initializes all beans, the method will be executed.
Application scenarios
Many times we want to do something when a certain class is loaded, but we use spring to manage objects. Our class refers to other classes (maybe more complicated associations). So when we use this class to do things, we find a package null pointer error. This is because our class may have been initialized, but the other classes referenced may not be initialized, so a null pointer error occurs.
The solution is as follows
1. Write an ApplicationListener listening class inheriting spring and monitor the ContextRefreshedEvent event (easy to initialize completion events)
2. Define a simple bean: <bean class=""></bean> or use the @Service annotation method directly
@Service public class StartListener implements ApplicationListener<ContextRefreshedEvent> { public static final Map<Integer, TableMapper> mappers = new HashMap<>(); @Resource A_Mapper a_mapper; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if(().getParent() == null)//root application context There is no parent, he is the boss. { //The logical code that needs to be executed will be executed when the spring container is initialized. ("\n\n\n\n\n\n____________________\n\n\n Loaded\n\n_____________\n"); } // Or the following method if(().getDisplayName().equals("Root WebApplicationContext")) { ("\n\n\n__________\n\n\n Loaded once \n\n _________\n\n\n\n\n"); } (1,a_mapper); } }
After the spring container is loaded, start a thread to update the data.
Requirements: Recently, I encountered a requirement for a project. Some data in the data table needs to be updated regularly, so I need to start a thread to complete it. I don’t want to create a new project to complete these things, so I want to start a thread to complete it regularly after spring starts. I will directly enter the code.
package ; import ; import ; import org.; import org.; import ; import ; import ; /** * Author: Wu Manxin * Date:2018/5/18 * Function: Responsible for updating the image and task data tables after the spring container is loaded */ @Component public class SpringFinishedListener implements InitializingBean { private static final Logger logger = (); @Autowired private PictureService pictureService; @Autowired private TaskService taskService; @Override public void afterPropertiesSet() throws Exception { new Thread(() -> { while (true) { ("Start the update operation of pictures and tasks!"); try { (); //Update the completion status information of the task (); } catch (Exception e) { (); (()); } try { (1800000); // Perform data update once every 30 minutes } catch (InterruptedException e) { (); (()); } } }).start(); } }
I have also tried servlet methods at the beginning, such as
package ; import org.; import org.; import ; import ; import ; /** * Author: Wu Manxin * Date:2018/5/18 * Function: */ @WebServlet(name = "backServlet", urlPatterns = {"/backServlet"}) public class BackServlet extends HttpServlet { private static final Logger logger= (); @Override public void init() throws ServletException { new Thread(()->{ while(true){ ("I execute it once in 5 seconds"); try { (5000); } catch (InterruptedException e) { (()); } } }).start(); } @Override public void destroy() { ("The server is closed"); } }
Configure Configuration
package ; import ; import ; import ; import ; import ; import ; /** * Author: Wu Manxin * Date:2018/5/15 * Function: */ @Configuration public class SpringConfiguration { @Bean public HandlerExceptionResolver getHandlerExceptionResolver() { return new MyExceptionResolver(); } /** * Configure a servlet running in the background * @return */ @Bean public ServletRegistrationBean servletRegistrationBean() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new BackServlet(), "/backServlet"); (1); //The smaller the number, the higher the startup priority, but it must be greater than 0 return servletRegistrationBean; } }
However, after spring starts, if spring does not complete, the bean cannot be used, so we follow the previous method
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.