Spring 基本概念
1 spring是开源的轻量级框架
2 spring核心主要两部分:
(1)aop:面向切面编程,扩展功能不是修改源代码实现
(2)ioc:控制反转,把对象的创建交给spring进行管理
- 比如有一个类,在类里面有方法(不是静态的方法),调用类里面的方法,创建类的对象,使用对象调用方法,创建类对象的过程,需要new出来对象
- 把对象的创建不是通过new方式实现,而是交给spring配置创建类对象
3 spring是一站式框架
(1)spring在javaee三层结构中,每一层都提供不同的解决技术
- web层:springMVC
- service层:spring的ioc
- dao层:spring的jdbcTemplate
开发中的一种思想: 高内聚,低耦合
原始的管理bean 的方式,是在对象里面new 的方式,但是这样耦合度太高了
解决方法: 工厂模式解决
Spring 解决 — IOC原理
ioc底层原理使用技术
(1)xml配置文件
(2)dom4j解决xml
(3)工厂设计模式
(4)反射
bean 标签的常用属性
- id 属性
bean 的唯一标识,一般是以类名命名,首字母小写(可以是任意名字,但不能包含特殊符号) - class 属性
创建对象所在类的全路径 - name 属性
和 id 的功能是一样的(可以包含特殊符号) scope 属性
- singleton:默认值,单例
- prototype:多例
- request:创建对象把对象放到request域里面
- session:创建对象把对象放到session域里面
- globalSession:创建对象把对象放到globalSession里面
autowire 属性注入方式
- byName:把与bena 的属性具有相同名字id的自动装配到所在bean中
- byType: 把与bean 的属性具有相同类型的其他bean注入到对应到对应属性中
- constructor :构造函数注入
- autodetect:最佳装配方式,先按照constructor注入,如果失败,按照byType方式注入
ps: 可以在bean里面为每一个bean单独设置,也可以在xml文件的头部添加整个xml文件中bean 的注入方式。
属性注入
- 构造函数注入
<!-- 使用有参数构造注入属性 -->
<!-- <bean id="demo" class="cn.itcast.property.PropertyDemo1"> -->
<!-- 使用有参构造注入 -->
<!-- <constructor-arg name="username" value="小王小马"></constructor-arg>
</bean> -->
- setter 方法注入
<!-- 使用set方法注入属性 -->
<!-- <bean id="book" class="cn.itcast.property.Book"> -->
<!-- 注入属性值
name属性值:类里面定义的属性名称
value属性:设置具体的值
-->
<property name="bookname" value="易筋经"></property>
</bean>
注入复杂数据类
数组
List
Map
properties
<!-- 注入复杂类型属性值 -->
<bean id="person" class="cn.itcast.property.Person">
<!-- 数组 -->
<property name="arrs">
<list>
<value>小王</value>
<value>小马</value>
<value>小宋</value>
</list>
</property>
<!-- list -->
<property name="list">
<list>
<value>小奥</value>
<value>小金</value>
<value>小普</value>
</list>
</property>
<!-- map -->
<property name="map">
<map>
<entry key="aa" value="lucy"></entry>
<entry key="bb" value="mary"></entry>
<entry key="cc" value="tom"></entry>
</map>
</property>
<!-- properties -->
<property name="properties">
<props>
<prop key="driverclass">com.mysql.jdbc.Driver</prop>
<prop key="username">root</prop>
</props>
</property>
</bean>
IOC 和 DI
(1)IOC: inversion of control 控制反转,把对象创建交给spring进行配置
(2)DI: dependency injection 依赖注入,向类里面的属性中设置值
(3)关系:依赖注入不能单独存在,需要在ioc基础之上完成操作
说明: 本文大部分内容都是跟随者传播智课的教学视频学习而来,可以看做是翻译文章,只是自己吸收之后又书写一遍,加深自己的知识理解。