Java中如何获取Spring中配置的bean
一什么是Spring?
Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架
二如何在程序中获取Spring配置的bean呢?
方法一在初始化时保存ApplicationContext对象
代码
ApplicationContextac=newFileSystemXmlApplicationContex(applicationContextxml);acgetBean(beanId); ApplicationContextac=newFileSystemXmlApplicationContex(applicationContextxml);
acgetBean(beanId);说明这种方式适用于采用Spring框架的独立应用程序需要程序通过配置文件手工初始化Spring的情况
方法二通过Spring提供的工具类获取ApplicationContext对象
代码
importsprntextsupportWebApplicationContextUtils;ApplicationContextac=WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContextsc)ApplicationContextac=WebApplicationContextUtilsgetWebApplicationContext(ServletContextsc)acgetBean(beanId);acgetBean(beanId);importsprntextsupportWebApplicationContextUtils;ApplicationContextac=WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContextsc)ApplicationContextac=WebApplicationContextUtilsgetWebApplicationContext(ServletContextsc)acgetBean(beanId);acgetBean(beanId); 方法三继承自抽象类ApplicationObjectSupport
说明抽象类ApplicationObjectSupport提供getApplicationContext()方法可以方便的获取到ApplicationContextSpring初始化时会通过该抽象类的setApplicationContext(ApplicationContextcontext)方法将ApplicationContext对象注入
方法四继承自抽象类WebApplicationObjectSupport
说明类似方法三调用getWebApplicationContext()获取WebApplicationContext
方法五实现接口ApplicationContextAware
lishixinzhi/Article/program/Java/ky/201311/28587
免责声明:本站发布的教育资讯(图片、视频和文字)以本站原创、转载和分享为主,文章观点不代表本网站立场。
如果本文侵犯了您的权益,请联系底部站长邮箱进行举报反馈,一经查实,我们将在第一时间处理,感谢您对本站的关注!
新励学网教育平台
海量全面 · 详细解读 · 快捷可靠
累积科普文章数:18,862,126篇