First, the interface
Public InterfaceInitializingbean {/*** Invoked by a beanfactory after it have set all beans properties supplied * (and satisfied beanfactoryaware an D applicationcontextaware). * <p>this method allows the bean instance to perform initialization if * possible when all bean properties hav e been set and to throw a * exception in the event of misconfiguration. * @throwsException in the event of misconfiguration (such * as failure to set a essential property) or if initialization Fails. */ voidAfterpropertiesset ()throwsException;}
Second, the role
Use spring's Initializingbean Afterpropertiesset to initialize and look directly at the demo below
①, interface definition
Public Interface Initializingservice { publicvoid Say ();}
②, interface implementation class
@Component ("Initializingservice")publicclassimplements Initializingservice, Initializingbean { @Override publicvoidthrows Exception { System.out.println ("Call Initializingbean"); } @Override publicvoid say () { System.out.println ("call say") ; }}
③, get bean context tool class implementation
Public classSpringcontextutilImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext;//Spring Application Context Environment@Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {springcontextutil.applicationcontext=ApplicationContext; } /*** Get the object * *@paramname *@returnObject An instance of the bean registered with the given name *@throwsbeansexception*/ Public StaticObject Getbean (String name)throwsbeansexception {returnApplicationcontext.getbean (name); }}
XML configuration: Spring XML file injection
<id= "Springcontextutil" class= " Com.mycompany.yuanmeng.springdemo.aop.SpringContextUtil "/>
④, testing
Public class Initializingbeandemo { publicstaticvoid main (string[] args) { New// load ApplicationContext (analog start Web service) = (initializingservice ) Springcontextutil.getbean ("Initializingservice"); Service.say (); }}
⑤, results
Call Initializingbeancall say
This means that when spring initializes the bean, the Afterpropertiesset method is called automatically if the Bean implements the Initializingbean interface.
Spring Initializingbean Interface