做了3年开发,都有用到spring, 简单对获取bean的总结。
1. 最简单的读取配置文件main方法加载
BeanFactory、ApplicationContext两个类加载:
1.1:BeanFactory加载
Resource resource =new FileSystemResource("beans.xml");
BeanFactory factory =new XmlBeanFactory(resource);factory.getBean("beanId");
Resource 有多个实现类去加载不同的配置文件
1.2:ApplicationContext加载:
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
String[] strs={"beans1.xml","beans2.xml"}; /*多个配置文件, 也可以一个配置文件*/
ApplicationContext context =new ClassPathXmlApplicationContext(strs);
context.getBean("beanId");
ApplicationContext的常用实现类为ClassPathXmlApplicationContext
2.web开发中需要从ServletContext加载,这一类通常先通过spring listener 加载好IOC容器,然后通过servletContext获取的bean
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
ServletContext可以通过servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext()获取,
当然也可以直接从ServletContext中直接获取到WebApplicationContext对象,具体方法为
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
3.实现接口ApplicationContextAware
实现该接口的setApplicationContext (ApplicationContext context)方法,并保存ApplicationContext对象,同时需要在spring.xml中配置这个对象bean
public class MyApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;//声明一个静态变量保存
public void setApplicationContext(ApplicationContext contex) throws BeansException {
this.context=contex;
}
}
//spring.xml
<bean class="org.ing.springutil.MyApplicationContextUtil"></bean>
4.另外没有用过的两种方式
4.1:继承自抽象类ApplicationObjectSupport
4.2:继承自抽象类WebApplicationObjectSupport