优势
-
方便解耦,简化开发
通过Spring提供的IoC容器,可以将对象间的依赖关系交由Spring进行控制,避免硬编码所造成的过度耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,更加专注与上层的应用。 -
AOP编程的支持
许多不容易用传统OOP实现的功能可以通过AOP轻松实现。 -
声明式事务的支持
-
方便程序的测试
-
方便集成各种优秀的框架
-
降低JavaEE API的使用难度
-
Java源码是经典学习范例
Spring的体系结构
Spring程序开发步骤
- 导入Spring开发的基本包坐标
- 编写Dao接口和实现类
- 创建Spring核心配置文件
- 在Spring配置文件中配置UserDaoImpl
- 使用Spring的API获取Bean实例
Spring配置文件
-
Bean标签配置范围
-
Bean实例化的三种方式
- 无参构造方法实例化
- 工厂静态方法实例化
- 工厂实例方法实例化
-
Bean的依赖注入
依赖注入是Spring框架核心IOC的具体实现,总结一句话,框架把持久层对象传入业务层,而不用我们自己去获取。 -
Bean的依赖注入的数据类型
- 普通数据类型
- 引用数据类型
- 集合数据类型
-
引入其他配置文件(分模块开发)
<import resource="applicationContext-xxx.xml"/>
总结Spring的重点配置
<bean>标签
id属性:在容器中Bean实例的唯一标识,不允许重复
class属性:要实例化的Bean的全限定名
scope属性:Bean的作用范围,常用Singleton(默认)和prototype
<property>标签:属性注入
name属性:属性名称
value属性:注入的普通属性值
ref属性:注入的对象引用值
<list>标签
<map>标签
<properties>标签
<constructor-age>标签
同上
<import>标签:导入其它的Spring的分文件
Spring相关API
ApplicationContext app = new ClassPathXmpApplicationContext("xxx.xml");
app.getBean("id");
app.getBean(Class);
Spring配置数据源
常用的数据源(连接池:DBCP、C3P0、BoneCP、Druid等
- 数据源的开发步骤
- 导入数据源的坐标和数据库驱动坐标
- 创建数据源对象
- 设置数据源的基本连接数据
- 使用数据源获取连接资源和归还连接资源
Spring容器加载properties文件
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
Spring原始注解
@Resource相当于@Qualifier + @Autowired
Spring新注解
使用原始注解还不能全部替代xml配置文件,不能替代的配置有:
- 非自定义的Bean的配置:
<bean>
- 加载properties文件的配置:
<context:property-placeholder>
- 组件扫描的配置:
<context:component-scan>
- 引入其他文件:
<import>
所以,新注解出现了…
Spring集成Junit
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
- 将需要进行测试Bean直接在测试类中进行注入