spring ioc主要用到了工厂设计模式和反射的技术,在spring中定义的类型统称为bean,创建bean的工厂是BeanFactory,ApplicationContext是BeanFactory的子接口,是我们常用的类型,这个接口有三个实现分别是
ClassPathXmlApplicationConext:直接在src根目录查找XML配置文件
FileSystemXmlApplicationConext:通过制定XML配置文件的绝对路径来加载配置文件
ContextLoaderListener:在web服务器中自动加载配置文件
附demo
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("application.xml");
TestDao dao= (TestDao)context.getBean("test");
dao.sayHello();
}
public static void main(String[] args) {
ApplicationContext context= new FileSystemXmlApplicationContext("D:\\spring-workspace\\demo1\\src\\main\\java\\application.xml");
TestDao dao= (TestDao)context.getBean("test");
dao.sayHello();
}
ContextLoaderListener使用需要在web.xml中进行配置,web.xml通常在webapp/WEB-INF/文件夹下
<servlet>
<servlet-name>springmvc01</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
ApplicationContext applicationContext = (WebApplicationContext) request.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
DemoService service = (DemoService) applicationContext.getBean("demoServiceImpl");
service.sayHello();