Spring中如何靜態持有ApplicationContext對象
關注我們 http://xingchenxueyuan.com 更多知識和內容,一起打怪升級!
我們在寫spring時,可能需要在Controller中引用appContext來獲取需要的bean或者配置,這時候就需要把實例化的spring context對象進行保存,在這里我們使用靜態變量的方法進行保存。
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
*
*以靜態變量保存Spring ApplicationContext, 可在任何代碼任何地方任何時候中取出ApplicaitonContext.
*/
@Component
public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;
//實現ApplicationContextAware接口的context注入函數, 將其存入靜態變量.
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
//取得存儲在靜態變量中的ApplicationContext.
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder");
}
}
}
...
//在相應的controller中我們就可以直接引用
@RestController
class MyController{
@RequestMapping(value = "/pro")
@ResponseBody
public Object getPro(@RequestParam String name){
return SpringContextHolder.getApplicationContext().getEnvironment().getProperty(name);
}