Spring container loads and executes a method. spring container loads and runs
Today, I encountered a problem. I need to add a timer to the project and execute the timer after the project is started. So what are the methods to be executed after spring container Initialization on the Internet:
I checked a lot of information and found two methods that met the conditions. I used them to talk about my personal understanding based on the information on the Internet:
1. Write a class to implement BeanPostProcessor. This interface has two methods:
(1) postProcessBeforeInitialization method, which is called before bean initialization defined in spring;
(2) postProcessAfterInitialization method, which is called after bean initialization defined in spring;
First, I tried this method and found that this interface is called every time a bean is initialized when the spring container is started. That is to say, how many beans do you initialize, the number of calls returned does not meet my previous requirements;
2. Then I found another method and wrote a class to implement the InitializingBean interface:
(1) to implement this interface, you only need to implement the afterPropertiesSet () method and write the code to be preprocessed in it. After the spring container is started, the method in it will be executed.
Obviously, the last one meets my needs. I write the timer code in the afterPropertiesSet () method of the class implementing the InitializingBean interface.
Public class DayTradeTimer implements InitializingBean {/*****/private static final long serialVersionUID =-response; @ SuppressWarnings ("deprecation") public void afterPropertiesSet () throws Exception {// TODO Auto-generated method stubDate date = new Date (); // execute if (date. getHours () = 2 & date. getMinutes ()> 0) | (date. getHours ()> 2) {date. setDate (date. getDate () + 1);} date. setHours (2); date. setMinutes (0); date. setSeconds (0); Timer timer = new Timer (); timer. scheduleAtFixedRate (new TimerTask () {@ Overridepublic void run () {// TODO Auto-generated method stubSystem. out. println ("***************************"); }}, date, 1000*60*60*24 );}}
Finally, paste a method that the servlet executes when the web Container starts.
<Servlet> <servlet-name> myServlet </servlet-name> <servlet-class> com. servlet. myServlet </servlet-class> <load-on-startup> 1 </load-on-startup> <! -- Add this label to automatically load the specified servlet when tomcat starts. The value is the servlet loading sequence. A smaller number indicates a higher loading priority. --> </servlet>
After spring is started with tomcat and Initialization is complete, a class is automatically executed once. How can this problem be solved?
Use spring quartz
How can I determine whether Spring container Initialization is complete?
It should be okay.
@ Qualifier ("C ")?
Are you sure the C Name is correct?
If the name is unique, remove @ Qualifier ("C ").