Reprinted from: http://penghuaiyi.iteye.com/blog/2042296
Scene:
Need to dynamically get spring-managed beans in your code
Code:
Springcontextutils.java
Packagecom.winner.utils;Importorg.springframework.beans.BeansException;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware;Importorg.springframework.stereotype.Component;/*** Spring's tool class, used to get the bean in the config file*/@Component Public classSpringcontextutilsImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext; /*** When the Applicationcontextaware class is inherited, the program automatically calls the method when it calls Getbean (String), and does not operate on its own*/@Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {springcontextutils.applicationcontext=ApplicationContext; } /*** * Gets the corresponding bean in the configuration file according to the ID of a bean*/ Public StaticObject Getbean (String Beanid)throwsbeansexception {if(Applicationcontext.containsbean (Beanid)) {Applicationcontext.getbean (Beanid); } return NULL; } /*** * Gets the corresponding bean in the configuration file according to the type of a bean*/ Public Static<T> T Getbeanbyclass (class<t> requiredtype)throwsbeansexception {returnApplicationcontext.getbean (requiredtype); } /*** Returns True if Beanfactory contains a bean definition that matches the given name*/ Public Static BooleanContainsbean (String name) {returnApplicationcontext.containsbean (name); } Public StaticApplicationContext Getapplicationcontext () {returnSpringcontextutils.applicationcontext; }}
The packages where these annotations are
<Dependency> <groupId>Org.springframework</groupId> <Artifactid>Spring-context</Artifactid> <version>4.2.5.RELEASE</version></Dependency>
springcontextutils must be placed in the spring container
Either declare it in an XML configuration file, or add annotations
Dynamically acquiring beans by implementing the Applicationcontextaware interface