Spring是如何管理Bean
容器是什么?spring中是如何体现的?一直有疑惑,这两天看了一下Spring管理bean的Demo,对于Spring中的容器有了简单的认识。
我们知道,容器是一个空间的概念,一般理解为可盛放物体的地方。在Spring容器通常理解为BeanFactory或者ApplicationContext。我们知道spring的IOC容器能够帮我们创建对象,对象交给spring管理之后我们就不用手动去new对象。
其中有BeanFactory与ApplicationContext两种方式可以创建对象。
那么BeanFactory与ApplicationContext的区别是什么?
BeanFactory采用了工厂设计模式,负责读取bean配置文档,管理bean的加载,实例化,维护bean之间的依赖关系,负责bean的声明周期。而ApplicationContext除了提供上述BeanFactory所能提供的功能之外,还提供了更完整的框架功能:国际化支持、aop、事务等。同时BeanFactory在解析配置文件时并不会初始化对象,只有在使用对象getBean()才会对该对象进行初始化,而ApplicationContext在解析配置文件时对配置文件中的所有对象都初始化了,getBean()方法只是获取对象的过程。
所以ApplicationContext的应用场景更广泛。
ApplicationContext是如何管理Bean呢?下面这个Demo简单模仿了这个原理:
1.建立一个类PersonServiceBean,并在xml文件中进行配置。
public class PersonServiceBean implements PersonService {
public void save(){
System.out.println("我是save()的方法");
}
}
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
2.建立类BeanDefinition,提供一个构造函数,将其作为每个bean的公共转型类。
public class BeanDefinition {
private String id;
private String className;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
//get set方法
}
3.建立容器类tgbApplicationContext。
/**
* 测试spring容器
* @author hegang
*
*/
public class tgbClassPathXMLApplicationContext { private List<BeanDefinition> beanDefines =new ArrayList<BeanDefinition>();
private Map<String,Object> sigletons =new HashMap<String,Object>(); public tgbClassPathXMLApplicationContext(String filename){
this.readXML(filename);
this.instanceBeans();
} /**
* 完成bean的实例化
*/
private void instanceBeans() {
for(BeanDefinition beanDefinition : beanDefines){
try {
if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim())){
sigletons.put(beanDefinition.getId(),Class.forName(beanDefinition.getClassName()).newInstance());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } } /**
* 读取xml配置文件
* @param filename
*/
private void readXML(String filename) {
SAXReader saxReader = new SAXReader(); //创建读取器
Document document =null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(filename);
document =saxReader.read(xmlpath);
Map<String,String> nsMap =new HashMap<String,String>();
nsMap.put("ns","http://www.springframework.org/schema/beans"); //加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean"); //创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap); // 设置命名空间
List<Element> beans = xsub.selectNodes(document); // 获取文档下所有的bean节点
for(Element element:beans){
String id =element.attributeValue("id"); // 获取id属性值
String clazz =element.attributeValue("class"); // 获取class属性值
BeanDefinition beanDefine =new BeanDefinition(id,clazz);
beanDefines.add(beanDefine);
} } catch(Exception e){
e.printStackTrace();
} } /**
* 获取bean实例
* @param beanName
* @return
*/
public Object getBean(String beanName){
return this.sigletons.get(beanName);
}
}
该类中拥有一个List<BeanDefinition>泛型集合类以及一个Map<String,Object>集合。通过查看代码我们知道这个容器类所做的事情如下:
a.读取配置文件bean.xml,并根据文件中bean的id,class属性实例化一个BeanDefinition,装入泛型集合中。
b.通过循环+反射,将List<BeanDefinition>中的bean加入到Map<String,Object>中,这里用反射将bean中的className属性转换为一个实例化的bean对象加入到了Map中。
c.提供一个对外的接口,通过传入参数获取该bean。
4.下面就是通过容器类获取具体bean的代码了。
public class SpringTest {
@Test
public void instanceSpring(){
tgbClassPathXMLApplicationContext ctx =new tgbClassPathXMLApplicationContext("beans.xml");
PersonService personService =(PersonService) ctx.getBean("personService");
personService.save();
}
}
通过这样的Demo,可以清楚看到Spring容器做的事情。它在初始化的时候将配置文件中bean以及相对应关系的配置都加入到ApplicationContext,通过一系列的转换将这些bean实例化,bean被它进行了管理,所以ApplicationContext就扮演了一个容器的角色。
Spring是如何管理Bean的更多相关文章
- (转)让Spring自动扫描和管理Bean
http://blog.csdn.net/yerenyuan_pku/article/details/52861403 前面的例子我们都是使用XML的bean定义来配置组件.在一个稍大的项目中,通常会 ...
- Spring、Spring自动扫描和管理Bean
Spring2.5为我们引入了组件自动扫描机制,它可以在类路径下寻找标记了@Component.@Service.@Controller.@Repository注解的类,并把这些类纳入到spring容 ...
- Spring第八发—自动装配及让Spring自动扫描和管理Bean
依赖注入–自动装配依赖对象(了解即可) 对于自动装配,大家了解一下就可以了,实在不推荐大家使用.例子: byName:按名称装配,可以根据属性的名称,在容器中寻找跟该属性名相同的bean,如果没有找到 ...
- 使用Spring和SpringMVC管理bean时要注意的一个小细节
最近一直在做毕业设计...用到了Shiro和SpringMVC..用过shiro的朋友都知道shiro需要自己去写Realm,然后把Realm注入到SecurityManager中.而Security ...
- Spring中管理Bean以及解析XML
Spring是分层的轻量级框架 以IoC(Inverse of Control 反转控制)和AOP(Aspect Oriented Programming 面向切面编程)为核心 应用Spring的好处 ...
- 采用Spring管理Bean和依赖注入
1. 实例化spring容器和从容器获取Bean对象 实例化Spring容器常用的两种方式: 方法一: 在类路径下寻找配置文件来实例化容器 [推荐使用] ApplicationContext ctx ...
- Spring的依赖注入和管理Bean
采用Spring管理Bean和依赖注入 1.实例化spring容器 和 从容器获取Bean对象 实例化Spring容器常用的两种方式: 方法一: 在类路径下寻找配置文件来实例化容器 [推荐使用] Ap ...
- spring总结之一(spring开发步骤、bean对象的管理、bean生命周期)
###spring 1.概念:开源,轻量级,简化开发的企业级框架. 开源:免费,发展快. 轻量级:占内存小. 简化开发:通用的功能封装,提高程序员的开发效率.--------------------- ...
- Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)
在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...
随机推荐
- NMS_非极大值抑制(转)
NMS(non maximum suppression),中文名非极大值抑制,在很多计算机视觉任务中都有广泛应用,如:边缘检测.目标检测等. 这里主要以人脸检测中的应用为例,来说明NMS,并给出Mat ...
- CopyOnWriteArrayList的增删改查实现原理
https://www.cnblogs.com/simple-focus/p/7439919.html 篇文章的目的如下: 了解一下ArrayList和CopyOnWriteArrayList的增删改 ...
- java——斗地主小游戏之洗牌发牌
遇到的问题: 1.int和Integer的区别? 1)Integer是int的包装类,int则是java的一种基本数据类型 . 2)Integer变量必须实例化后才能使用,而int变量不需要 . 3) ...
- 异地clone RAC数据库 +ASM USE RMAN
###sample 如何在本地生成数据库的备份,并复制到DG库新环境(高级) 1. 首先确定本地文件系统(存放备份集)足够大,可以使用如下语句查询当前数据库实际的使用总大小 Rman 备份进度: se ...
- spring配置文件中util:properties和context:property-placeholder
util:properties和context:property-placeholder标签都可以用来获取外部配置文件中的内容 1.util:properties 它是以声明bean方式来使用,创建了 ...
- indexOf 可用于字符串和数组
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置. indexOf 与String类似,Array也可以通过indexOf()来搜索一个指定的元素的位置: var arr = ...
- TestNG的testng.xml配置概述
TestNG提供的annotaions用来辅助定义测试类. TestNG的testng.xml配置文件用来辅助定义执行什么样的测试,即testng.xml更像是一个测试规划. testng.xml配置 ...
- Robot Framework搭建
需要安装的内容如下: 1. Python2.7.13(听说python3对RF支持的不是很好,所以我下的Python2) 2. wxPython 2.8.12.1(只能这个版本) 3. robotfr ...
- 性能测试工具LoadRunner24-LR之Analysis 系统资源分析
1.内存分析方法 内存分析方法主要是用于判断系统有无遇到内存瓶颈,是否需要通过增加内存等手段提高系统性能表现.主要计数器包括Memory和Physical Disk类别的计数器 内存分析的主要步骤和方 ...
- instancemethod, staticmethod, classmethod & abstractmethod
实例方法.静态方法.类方法.抽象方法 1. Python中方法的工作方式(How methods work in Python) A method is a function that is sto ...