In the development of Web projects, especially enterprise application development, often when the project started to do a lot of pre-check.
For example, check if we use the Group_concat function of MySQL that our group forbids to use, if we use the project, we can't start it, and indicate which file's XML file uses this function.
In spring's Web project, we can intervene in spring's startup process. We want to do something after the spring container initializes all the beans, and at this point we can implement an interface:
Package Com.yk.test.executor.processor Public class Implements Applicationlistener<contextrefreshedevent> {@Overridepublicvoid Onapplicationevent (Contextrefreshedevent event) {// The logic code that needs to be executed is executed when the spring container initialization is complete. }}
Also in spring's configuration file, add the injection:
<!---<class= " Com.yk.test.executor.processor.InstantiationTracingBeanPostProcessor "/>
But this time, there is a problem, in the Web project (Spring MVC), the system will have two containers, one is the root application context, and the other is our own projectname-servlet Context (as a sub-container of root application context).
In this case, it causes the Onapplicationevent method to be executed two times. In order to avoid the above mentioned problem, we can only call the logic code after the root application context initialization completes, the other container initialization completes, then does not do any processing, the modified code
As follows:
@Override Public void onapplicationevent (Contextrefreshedevent event) {ifnull) {//Root Application Context No parent, he is the boss. // The logic code that needs to be executed, which executes when the spring container is initialized. }}
The simplest way to do this is to use the note: ' @PostConstruct ', just mark the annotation on the method you want to execute when you need to start.
Example:
/*** Execute when service starts--Add Super Administrator*/@PostConstruct Public voidadddefaultadmin () {Try{User User=NewUser (); User.setcreatetime (NewDate ()); Try{User.setpassword (Md5.md5encode ("Admin")); } Catch(Exception e) {e.printstacktrace (); } user.setusername ("Admin"); User.setrole (frameconstant.user_super_admin); Userdao.save (user); Log.debug ("Initialization is complete!" "); } Catch(Exception e) {log.debug ("Initialization is complete!" "); } }
Executes a method after the spring container initialization is complete