On the premise of SSH integration. In some cases, we need to obtain the service object managed by spring in a class other than action.
I haven't found a proper method for a long time on the Internet before. For example:
Applicationcontext context = new classpathxmlapplicationcontext ();
At that time, I didn't think it was necessary to waste memory. Then I finally came up with a solution. For your reference, I hope to help you.
1. Create a class and implement the org. springframework. Context. applicationcontextaware interface to inject applicationcontext objects to spring at startup.
ExampleCode:
View plaincopy to clipboardprint?
Import org. springframework. Beans. beansexception;
Import org. springframework. Context. applicationcontext;
Import org. springframework. Context. applicationcontextaware;
Public class myapplicationcontextutil implements applicationcontextaware {
Private Static applicationcontext context; // declare a static variable to save
@ Override
Public void setapplicationcontext (applicationcontext contex)
Throws beansexception {
This. Context = contex;
}
Public static applicationcontext getcontext (){
Return context;
}
2. Configure the bean in the applicationcontext. xml file so that the applicationcontext object is automatically injected to us during spring startup.
Example:
<! -- This bean is mainly used to obtain applicationcontext, so it does not need other attributes -->
<Bean class = "org. Ing. springutil. myapplicationcontextutil"> </bean>
3. With this applicationcontext, we can call its getbean ("beanname") method to get all objects managed by spring.