自定义一个工具类,实现自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;
}
}
如果使用@Autowired注解自动装配的话,继承SpringBeanAutowiringSupport类是不能少的。当然,使用@Component等注解也是可以的。使用注解的话配置就需要改动了,不过因为我们为支持Spring注解的配置是可以多用的,所以还好。如下:
<context:component-scan base-package="org.ahe"></context:component-scan>
该配置即可让org.ahe下所有包(您依然可以通过子标签的正则表达式匹配来进行更多设置)下的注解起作用。