最近在做项目的时候我发现一个问题:Spring的IOC容器不能在Web中被引用(或者说不能被任意地引用)。我们在配置文件中让Spring自动装配,但并没有留住ApplicationContext的实例。我们如果希望在我们的项目中任何位置都能拿到同一个ApplicationContext来获取IOC容器中的资源,就要让Spring将上下文环境填充到我们能获取的地方,比如下面的做法(来自网络资源):
自定义一个工具类,实现自ApplicationContextAware接口,接口的方法是setApplicationContext,我们实现它,并让其为我们服务,因为Spring在load自己的时候会将上下文环境填充进来。我们所要做的就是将得到的ApplicationContext保存下来用。
package org.coderecord.ccms.web.action.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring IOC上下文工具类
*
* @author Ryan Shaw
*
*/
public class SpringUtil implements ApplicationContextAware {
/**
* 当前IOC
*/
private static ApplicationContext applicationContext;
/**
* 设置当前上下文环境,此方法由spring自动装配
*/
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
applicationContext = arg0;
}
/**
* 从当前IOC获取bean
*
* @param id
* bean的id
* @return
*/
public static Object getObject(String id) {
Object object = null;
object = applicationContext.getBean(id);
return object;
}
}
上文的类就是我们要用的,而其中的setApplicationContext是接口中需要实现的,Spring会自动进行填充。我们在Spring的配置文件中注册一下:
<bean id="springUtil" class="org.coderecord.ccms.web.action.util.SpringUtil" />
这样就可以了,Spring把我们需要的东西给我们了。
我们就可以在需要的地方这样做:
YouClass obj = (YouClass)SpringUtil.getObject("beanid");
当然,前提是你需要让Spring自动装配哦。
以下为方法二,使用了注解和静态化的方式来产生SpringFactory对象
上文的方法有个麻烦的地方:需要配置。而Spring2.5及之后的版本实际上加入了注解的方式进行依赖项的注入,使用如下代码也许更好:
package org.ahe.util;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
public class SpringWiredBean extends SpringBeanAutowiringSupport {
/**
* 自动装配注解会让Spring通过类型匹配为beanFactory注入示例
*/
@Autowired
private BeanFactory beanFactory;
private SpringWiredBean() {
}
private static SpringWiredBean instance;
static {
// 静态块,初始化实例
instance = new SpringWiredBean();
}
/**
* 实例方法
* 使用的时候先通过getInstance方法获取实例
*
* @param beanId
* @return
*/
public Object getBeanById(String beanId) {
return beanFactory.getBean(beanId);
}
public static SpringWiredBean getInstance() {
return instance;
}
}
调用方法:
private CustomerService customerService = (CustomerService) SpringWiredBean.getInstance().getBeanById("customerService");