How does a non-spring hosted object obtain a spring hosted object?
Some thread classes or Servlets cannot call the classes in spring containers through spring annotations.
Failed to add @ component or @ controller annotation to thread or servlet to be managed by spring container, and then call other classes in spring container!
Finally, find the following two solutions:
1. initialize through spring configuration file applicationContext. xml
[Java] view plaincopy
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. FileSystemXmlApplicationContext;
Public class SpringUtil {
Private static ApplicationContext applicationContext = null;
Public static ApplicationContext getApplicationContext (){
If (applicationContext = null ){
ApplicationContext = new FileSystemXmlApplicationContext ("applicationContext. xml ");
}
Return applicationContext;
}
}
Disadvantages:
Here, applicationContext. xml is the full file path, which is one of the reasons why this method is not flexible,
When SpringUtil is called, an ApplicationContext object will be created. If static is removed and changed to non-static, a new object will be created each time this method is called, and the efficiency should be even worse.
2. Implement the ApplicationContextAware Interface
During spring initialization, The ApplicationContext object is injected into the class using the setApplicationComtext method implemented by this interface. For details, see the following
My solutions are as follows:
1. Define SpringUtil
Import org. springframework. beans. BeansException;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. ApplicationContextAware;
Public class SpringUtil implements ApplicationContextAware {
Private static ApplicationContext applicationContext;
Public static ApplicationContext getApplicationContext (){
Return applicationContext;
}
Public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
SpringUtil. applicationContext = applicationContext;
}
}
2. Add the spring configuration file
<Bean id = "applicationContext" class = "com. lefu. pushCore. other. SpringUtil"/>
3. You can get all objects managed by spring using the following method:
PushController pushController = (PushController) SpringUtil. getApplicationContext (). getBean ("pushController ");
Reference: http://blog.csdn.net/a19881029/article/details/7842070