2. ApplicationContext除了提供上述BeanFactory所能提供的功能之外,还提供了更完整的框架功能:
a. 国际化支持
b. 资源访问:Resource rs = ctx. getResource(“classpath:config.properties”), “file:c:/config.properties”
c. 事件传递:通过实现ApplicationContextAware接口
3. 常用的获取ApplicationContext的方法:
FileSystemXmlApplicationContext:从【文件系统】 或者 【classpath的xml配置文件】 创建,参数为配置文件名或文件名数组
ClassPathXmlApplicationContext:从【classpath的xml配置文件】创建,可以从【jar包】中读取配置文件
WebApplicationContextUtils:从web应用的根目录读取配置文件,需要先在web.xml中配置,可以配置监听器或者servlet来实现
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
这两种方式都默认配置文件为web-inf/applicationContext.xml,也可使用context-param指定配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>
public class BeanFactoryTest { public static void main(String[] args) throws Throwable{ ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("classpath:com/baobaotao/beanfactory/beans.xml"); System.out.println(res.getURL()); BeanFactory bf = new XmlBeanFactory(res); System.out.println("init BeanFactory."); Car car = bf.getBean("car",Car.class); System.out.println("car bean is ready for use!"); car.introduce(); } }
public class XmlApplicationContextTest { public static void main(String[] args) {
//如果配置文件放置在类路径下,用户可以优先使用ClassPathXmlApplicationContext实现类 ApplicationContext ctx = new ClassPathXmlApplicationContext("com/baobaotao/context/*.xml"); Car car1 = ctx.getBean("car",Car.class);
//如果配置文件放置在文件系统的路径下,则可以优先考虑使用FileSystemXmlApplicationContext实现类 // ctx = new FileSystemXmlApplicationContext("D:/com/baobaotao/context/*.xml"); // Car car2 = ctx.getBean("car",Car.class);
}
}