Many times, we need to get the spring bean in the ordinary Java class to do the operation, for example, in the thread, we need to manipulate the database, directly through the spring beans built in the service can be done. No need to write the link yourself. Sometimes there are some good things that you can get used to.
Here is one of many ways.
Get the bean by implementing applicationcontextaware. The problem here is that if the spring container does not start to complete, it cannot be obtained by this method, because the null pointer is reported because
private static ApplicationContext ApplicationContext;
This has not yet been loaded to completion. OK, start pasting the code.
Java class:
1 PackageCom.iafclub.demo.util;2 3 ImportJava.util.Map;4 5 ImportOrg.springframework.context.ApplicationContext;6 ImportOrg.springframework.context.ApplicationContextAware;7 8 /**Get JavaBean Tool class9 * Ten * @authorChenweixian One * A */ - Public classApplicationutilImplementsapplicationcontextaware{ - the Private StaticApplicationContext ApplicationContext; - - //Implement the context injection function of the Applicationcontextaware interface and store it in a static variable. - Public voidSetapplicationcontext (ApplicationContext applicationcontext) { +Applicationutil.applicationcontext =ApplicationContext; - } + A at //gets the applicationcontext stored in the static variable. - Public StaticApplicationContext Getapplicationcontext () { - Checkapplicationcontext (); - returnApplicationContext; - } - in //gets the bean from the static variable ApplicationContext and automatically transforms it into the type of the assigned value object. -@SuppressWarnings ("Unchecked") to Public Static<T>T Getbean (String name) { + Checkapplicationcontext (); - if(ApplicationContext = =NULL){ the return NULL; * } $ return(T) Applicationcontext.getbean (name);Panax Notoginseng } - the + //gets the bean from the static variable ApplicationContext and automatically transforms it into the type of the assigned value object. A //if more than one bean matches the class, remove the first one. the@SuppressWarnings ("Unchecked") + Public Static<T> T Getbean (class<t>clazz) { - Checkapplicationcontext (); $@SuppressWarnings ("Rawtypes") $Map Beanmaps =Applicationcontext.getbeansoftype (clazz); - if(beanmaps!=NULL&&!Beanmaps.isempty ()) { - return(T) beanmaps.values (). iterator (). Next (); the}Else{ - return NULL;Wuyi } the } - Wu Private Static voidCheckapplicationcontext () { - if(ApplicationContext = =NULL) { About //throw new IllegalStateException ("Applicaitoncontext not injected, please define Springcontextholder in Applicationcontext.xml"); $ } - } - -}
Configuration file:
1 < ID= "Applicationutil" class= " Com.iafclub.demo.util.ApplicationUtil "/>
Start complete.
Test: OK
1 (redistemplate<string, serializable>) Applicationutil.getbean ("Redistemplate");
Common Java classes How to get the Spring container bean