网上方法很多种,我说一些J2EE开发中会用到的方法。
第一种:
直接初始化Spring容器,获得对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
applicationContext.getBean("beanId");
关于配置文件的读取也有好多种,我用到的是配置文件在SRC下面。
这样会初始化Spring容器,然后再得到配置的对象。
第二种:
通过环境来获得
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
ac1.getBean("beanId");
ac2.getBean("beanId");
区别是前者会抛异常,而后者没有时返回NULL
第三种:
实现ApplicationContextAware接口
下面给出实现类,这也是我用的方法
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @说明 获得Spring配置中的某个对象
* @author 崔素强
* @see
*/
public class SpringFactory implements ApplicationContextAware {
private static ApplicationContext context;
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
public static Object getObject(String id) {
Object object = null;
object = context.getBean(id);
return object;
}
}
这是WEB开发中可以用到的集中方法,当然还有其他方法,欢迎大家积极提供!
请您到ITEYE看我的原创:http://cuisuqiang.iteye.com
或支持我的个人博客,地址:http://www.javacui.com