Spring如何获取Bean
编辑: 面试啦 发布时间: 2023-11-09 02:42:55
通过xml配置文件
bean配置在xml里面,spring提供多种方式读取配置文件得到ApplicationContext.
第一种方式:FileSystemXmlApplicationContext
通过程序在初始化的时候,导入Bean配置文件,然后得到Bean实例:
ApplicationContext ac = new FileSystemXmlApplicationContext(“applicationContext.xml”)
ac.getBean(“beanName”);
第二种方式:WebApplicationContextUtil
在B/S系统中,通常在web.xml初始化bean的配置文件,然后由WebAppliCationContextUtil得到ApplicationContext.例如:
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
其中 servletContext sc 可以具体 换成 servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext();
另外,由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
bean配置在xml里面,spring提供多种方式读取配置文件得到ApplicationContext.
第一种方式:FileSystemXmlApplicationContext
通过程序在初始化的时候,导入Bean配置文件,然后得到Bean实例:
ApplicationContext ac = new FileSystemXmlApplicationContext(“applicationContext.xml”)
ac.getBean(“beanName”);
第二种方式:WebApplicationContextUtil
在B/S系统中,通常在web.xml初始化bean的配置文件,然后由WebAppliCationContextUtil得到ApplicationContext.例如:
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
其中 servletContext sc 可以具体 换成 servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext();
另外,由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
词条:spring面试题
与该文相关的文章
- Spring框架的优点
- Strutc Spring Hibernate常见面试题
- Spring里面如何定义hibernate mapping
- 如何在web环境中配置applicationContext.xml文件
- Spring面试:什么是Spring, 它有什么特点
- Struts&Spring&Hibernate面试总结
- Struts,Spring,Hibernate面试题总结
- 在Spring框架中如何更加高效的使用JDBC
- spring中的BeanFactory与ApplicationContext的作用和区别
- spring的jdbc与传统的jdbc有什么区别,其核心类有那些?
面试题库导航
- C++面试题
- JAVA面试题
- Oracle面试题
- MySQL面试题
- Linux面试题
- 网络工程师面试题
- 网管面试题
- 软件工程师面试题
- PHP面试题
- .net面试题
- 软件测试面试题
- EJB面试题
- Spring面试题
- Javascript面试题
- Python面试题
- QTP面试题
- Servlet面试题
- J2EE面试题
- Database面试题
- ASP面试题
- Unix面试题
- Loadrunner面试题
- 通信面试题
- 嵌入式面试题
- Ruby面试题
- Delphi面试题
- Mobile开发面试题
- SOA面试题
- JAVA面试题面试题
- 研发工程师面试题
- 软件架构师面试题
- 系统工程师面试题
- Android面试题
- JAVA程序员
- C#面试题
面试题库更新
- Spring框架的优点
- Strutc Spring Hibernate常见面试题
- Spring里面如何定义hibernate mapping
- 如何在web环境中配置applicationContext.xml文件
- Spring面试:什么是Spring, 它有什么特点
- Struts&Spring&Hibernate面试总结
- Struts,Spring,Hibernate面试题总结
- 在Spring框架中如何更加高效的使用JDBC
- spring中的BeanFactory与ApplicationContext的作用和区别
- spring的jdbc与传统的jdbc有什么区别,其核心类有那些?