Spring 获取bean

方法一:

ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");

在applicationContent.xml中配置

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
5         //中间部分是你自己配置的所有bean

 

WEB项目:

方法1:

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)

方法2:

ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)

方法3:

写一个工具类类继承ApplicationObjectSupport,并将这个加入到spring的容器

方法4:

写一个工具类类继承WebApplicationObjectSupport,并将这个加入到spring的容器

 

方法1、2中使用ac.getBean("beanid");获取实例

  

 

posted @ 2018-08-23 16:20  爱,诗意永存  阅读(141)  评论(0编辑  收藏  举报