前言:
最近一直在学习spring,写这篇文章的目的出于对近期所学做一个总结,最主要的也是希望让大家重新认识下spring.讲到spring大家都会想到Ioc.,Ioc字面意思是控制反转。不知道大家小时候有没有一个习惯遇到不认识的单词先查新华字典。其实当我们遇到不认识的语句时可以查查维基百科英文版,看看它给出的解释.下面是维基百科对Ioc的解释。
In software engineering, inversion of control (IoC) is a programming principle. IoC inverts the flow of control as compared to traditional control flow. In IoC, custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as compared to traditional procedural programming: in traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the framework that calls into the custom, or task-specific, code.
说几个比较重的点:
1反转控制是相对于传统软件编程模型而言的。
2传统编程模型需要自己去调用可重复利用的lib,而对于反转控制而言这些都交给了框架。
3在谈起Ioc时,另外常常提起的的一个原则是好莱坞原则——导演在拍一部电影的时候,你们演员不要来找我,而是我们来找你。
可能讲到这里很多人可能有点晕,那么我在换个讲法,比如我们写一个普通的java程序时我们需要使用用户类,那么我们一般会这么写new User();熟悉Spring的同学知道应该这么写@Autowired User user(依赖注入),把初始化User的过程理解成你不来找我们我们来找你。那为什么要这么做呢?因为Spring就是一个容器,那么我们需要对每一个Bean有一个管理功能。事实上jdk自带的JavaBeans也是Ioc实现的一种方式,并且提供以下功能:
1依赖查找
2生命周期管理
3配置元信息
4事件
5自定义
6资源管理
7持久化
比如我们可以通过Java自省Introspector.getBeanInfo(User.class)依赖查找出相应的类对应的BeanInfo信息。其实到这里大家也可看出实现Ioc的方式有很多种,比如上文提到的依赖查找以及依赖注入,除此之外还有模板模式,策略模式等。到此已经对Ioc有了一个简单的讲解,接下来本文将对Spring各个模块做出一一的讲解。主要包括以下几个模块:
1前言
2SpringBean基础
3依赖查找
4依赖注入
5依赖来源
6SpringBean作用域
7SpringBean生命周期
8Spring配置元信息
9Spring资源管理
10Spring校验
11Spring数据绑定
12Spring类型转换
13范型处理
14Spring事件
15Spring注解
16SpringEnvironment
本文篇幅巨大且过于枯燥-大家可当作连续剧观看。
一、SpringBean基础
在jdk中我们可以通过BeanInfo来描述一个POJO对象,在spring中我们使用BeanDefinition接口来描述一个类。而BeanDefinition主要通过以下四个方面来描述一个Bean
1Bean的类名
2Bean的行为配置元素主要包括scope(作用域)autowired(自动绑定)bean生命周期回调等
3对其他Bean的引用如我们常见的xml中的ref元素
4属性(定义一个用户Bean,那么年龄,姓名等就是属性)
下图是BeanDefinition的一个总结: