First, Applicationcontextaware use
Spring provides the Applicationcontextaware class, through which you can get all the bean contexts.
Second, how to use?
①, define a tool class, to implement Applicationcontextaware, implement Setapplicationcontext method can
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); }}
②, business code
Public Interface Userreadservice { public UserInfo Getuserinfobyid (Long ID);} @Component ("Userreadservice")publicclassimplements Userreadservice { @Override public UserInfo Getuserinfobyid (Long id) { System.out.println ("Access to user Information") ; return NULL ; }}
③, XML configuration
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spri Ng-context-4.1.xsd "> <Context:annotation-config/> <!--automatic scanning contains @service to inject it into a bean - <Context:component-scanBase-package= "COM.MYCOMPANY.YUANMENG.SPRINGDEMO.AOP" /> <BeanID= "Springcontextutil"class= "Com.mycompany.yuanmeng.springdemo.aop.SpringContextUtil" /></Beans>
④, test
Public Static void Test () { new// load ApplicationContext (simulated start Web Service), of course, if it is a Web project, It can be configured directly on the Web. XML and the container will load the file. = (userreadservice) springcontextutil.getbean ("Userreadservice"); Userreadservice.getuserinfobyid (null); }
Spring Applicationcontextaware Get context