
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContextxml");//获取配置文件信息
Test1 test1=(Test1) contextgetBean("t1");//根据bean的id获得bean
test1show(test1getName(), test1getSex());
也可以用注解获取
@Resource //先按属性名查找 如果没有 再按属性类型查找
//以下两种注解 需要有setter 方法
@Autowired//按类型查找
@Qualifier("beanName")//按名字查找
private BizCheckResultDao bizCheckResultDao;
通过xml配置文件
bean配置在xml里面,spring提供多种方式读取配置文件得到ApplicationContext
第一种方式:FileSystemXmlApplicationContext
通过程序在初始化的时候,导入Bean配置文件,然后得到Bean实例:
ApplicationContext ac = new FileSystemXmlApplicationContext(applicationContextxml)
acgetBean(beanName);
第二种方式:WebApplicationContextUtil
在B/S系统中,通常在webxml初始化bean的配置文件,然后由WebAppliCationContextUtil得到ApplicationContext例如:
ApplicationContext ctx = WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ctx =�0�2�0�2 WebApplicationContextUtilsgetWebApplicationContext(ServletContext sc);
其中 servletContext sc 可以具体 换成 servletgetServletContext()或者 thisgetServletContext() 或者 requestgetSession()getServletContext();
另外,由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:
以上就是关于如何取得Spring管理的bean全部的内容,包括:如何取得Spring管理的bean、Spring如何获取Bean、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)