1、在初始化时保存ApplicationContext对象
适用于Spring框架的独立应用程序,须要程序通过配置文件初始化Spring。
applicationContext.xml
配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="test" class="com.sxtx.bean.Test">
</bean>
</beans>
代码:
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");
Test test= (Test) applicationContext.getBean("test");
System.out.println(test);
}
2、通过Spring提供的工具类获取ApplicationContext对象
适合于Spring框架的B/S系统,通过ServletContext
对象获取ApplicationContext
对象。然后在通过它获取须要的类实例。以下两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");