我认为此链接展示了即使在非bean类中,也可以在任何地方获取应用程序上下文的最佳方法。我觉得这很有用。希望对您一样。下面是它的抽象代码
创建一个新类ApplicationContextProvider.java
package com.java2novice.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
在application-context.xml中添加一个条目
<bean id="applicationContextProvider"
class="com.java2novice.spring.ApplicationContextProvider"/>
在注释情况下(而不是application-context.xml)
@Component
public class ApplicationContextProvider implements ApplicationContextAware{
...
}
获取这样的上下文
TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);
干杯!!