Spring框架中获取bean的五种方法
来源:互联网 发布:信鸽群发软件怎么样 编辑:程序博客网 时间:2024/05/29 05:02
原文地址是:http://blog.csdn.net/gaohuanjie/article/details/50895862。
获取bean的方法有五种,分别是:
(1) 第一种:在初始化时保存ApplicationContext对象
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
(2) 通过Spring提供的工具类获取ApplicationContext对象
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 =WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 =WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
第一种方式在获取失败时抛出异常,第二种方式返回null。
(3) 继承自抽象类ApplicationObjectSupport
通过抽象类ApplicationObjectSupport提供的getApplicationContext()方法可以方便的获取到ApplicationContext实例,进而获取Spring容器中的bean。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContextcontext)方法将ApplicationContext对象注入。
(4) 继承自抽象类WebApplicationObjectSuppo
(5) 实现接口ApplicationContextAware
说明:实现该接口的setApplicationContext(ApplicationContextcontext)方法,并保存ApplicationContext对象。Spring初始化时,会通过该方法将ApplicationContext对象注入。
public class SpringConfigTool implementsApplicationContextAware {// extends ApplicationObjectSupport{
privatestatic ApplicationContext ac = null;
privatestatic SpringConfigTool springConfigTool = null;
publicsynchronized static SpringConfigTool init() {
if(springConfigTool == null) {
springConfigTool= new SpringConfigTool();
}
returnspringConfigTool;
}
publicvoid setApplicationContext(ApplicationContext applicationContext)throwsBeansException {
ac= applicationContext;
}
publicsynchronized static Object getBean(String beanName) {
returnac.getBean(beanName);
}
}
其次在applicationContext.xml文件进行配置:
<bean id="SpringConfigTool"class="com.ghj.tool.SpringConfigTool"/>
最后通过如下代码就可以获取到Spring容器中相应的bean了:
SpringConfigTool.getBean("beanId");
- Spring框架中获取bean的五种方法
- Java普通类获取Spring框架Bean 的五种方法
- spring框架下获取Bean的两种常用方法
- spring框架下获取Bean的两种常用方法
- 获取Spring 容器中bean的方法
- spring 项目中获取bean 的方法
- 获取spring容器中bean的方法
- servletListener 中获取spring bean的方法
- servletListener中获取spring bean的方法
- Spring中获取bean的方法
- 获取Spring Bean 的几种方法.
- Spring获取bean的种方法
- spring获取bean的几种方法
- Spring框架中获取Bean实例
- Spring线程获取容器中bean的方法
- Filter或Servlet中获取Spring Bean的方法
- Spring框架下获取Bean的几种方式
- Spring框架下获取Bean的几种方式
- Android UpdateApk 增量更新
- JNDI的简单配置与使用
- SOCKET,TCP/IP,UDP,HTTP,FTP总结
- KVO的实现原理分析
- 一小时搞定DIV+CSS
- Spring框架中获取bean的五种方法
- 译码
- [思考]两个云计算平台的葬礼
- CAS单点登陆更改认证方式和持久化ticket
- 顺序表应用1:多余元素的删除之移位算法
- Thinking in Java
- alter table *** add constraint
- Android Studio多渠道打包方法
- post和get请求(xml)