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.processorpublic class Instantiationtracingbeanpostprocessor implements applicationlistener<contextrefreshedevent> {@Overridepublic void onapplicationevent (contextrefreshedevent Event) {//The logical code that needs to be executed, which executes when the spring container is initialized. }}
Also in spring's configuration file, add the injection:
<!--when the spring container starts, execute the following bean--><bean 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:
@Overridepublic void Onapplicationevent (Contextrefreshedevent event) {if (Event.getapplicationcontext (). GetParent () = = null) {//root application context no parent, he is the boss.//The logic code that needs to be executed is executed 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:
/** * Service start-up execution-add Super Administrator /@PostConstruct public void Adddefaultadmin () { try { User user = New User (); User.setcreatetime (New Date ()); 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 complete! "); } catch (Exception e) { Log.debug ("Initialization complete! "); } }
Executes a method after the spring container initialization is complete