Spring
1.什么是spring?
- spring是一个框架,核心技术是ioc和aop,实现解耦合
- spring是一个容器,容器中存储的是java对象
2.怎么使用spring?
- spring是一个容器,把项目中的对象放到容器中,
让容器来完成对象的创建,对象之间的关系的管理(属性赋值)
我们在程序中从容器中获取需要使用的对象
3.容器中放什么对象?
- dao类,service类,controller类,工具类
创建对象的方式:- 在xml配置文件,使用标签
- 注解
- spring中的对象默认都是单例的,在容器中叫这个名字的对象只有一个
4.容器中不该放的对象是什么?
- 实体类对象,实体类数据来自数据库的
- servlet,listener,filter等–>交给Tomcat进行管理创建
5.使用spring框架的步骤
1.加入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2.创建类:接口,实现类,没有接口的类
3.创建spring的配置文件,使用标签创建对象
4.使用容器中的对象:通过ClassPathXMLApplicationContext的得到ApplicationContext对象调用 getBean方法得到容器中的对象
6.核心技术
ioc:控制反转
- 1.理论,思想,概念:指导开发人员在容器中,代码之外管理对象,给属性赋值,管理依赖
- 2.ioc技术实现:di(依赖注入):开发人员在项目中只需要提供对象的名称,对象的创建,查找,赋值都由容器内部自己实现
- 3.spring使用的是di的技术,底层使用的是反射机制
- 4.给属性赋值
1. set注入,调用的是属性的set方法
---- 简单类型注入
---- 引用类型注入
2. 构造注入,调用的是带参构造方法
普通创建以及使用对象
1. 在main目录下资源文件resources目录下创建一个 applicationContext.xml文件
创建对象
<beans></beans>
跟标签
<bean></bean>
就是一个对象
bean标签属性:
id为对象的名称
class为映射文件的类路径
- 1.创建自定义对象
<bean id = "myStudent" class = "com.Students"/>
- 2.创建非自定义对象,有类即可创建对象
<bean id = "mydate" class = "java.unit.Date"/>
2.在测试方法中
- –创建并声明beans.xml的文件路劲 String config =
"applicationContext.xml";
- –通过new ClassPathXmlApplicationContext方法创建ApplicationContext对象
ApplicationContext ac = new ClassPathXMLApplicationContext(config);
- –通过getBean得到对象(强转)
Date mydate =(Date)ac.getBean("mydate");
getBean方法传参可以是id值等等 - –得到一个mydate对象,可以调用各种方法
给一个java对象的属性赋值
di:依赖注入,表示创建对象,给属性赋值 实现方法:
1. 基于XML的DI
①set注入
使用<property/>
标签
ps:name是对象属性名 value是对象属性值
注:该属性必须有set方法,spring底层只是执行了set方法
普通类型属性赋值
<bean id = "mystudent" class = "com.Student">
<property name = "name" value = "李四"/>
<!--引用类型属性赋值-->
<property name = "name" ref = "对象id"/>
</bean>
②构造注入
使用<constructor-arg/>
标签
通过有参构造方法,带参创建对象
标签属性
- name : 表示构造方法的形参名
- index : 表示构造方法的参数的位置,参数从左到右位置0-1-2的顺序
- value : 构造方法的类型参数是简单类型时
- ref : 构造方法的类型参数是引用类型时
- –使用name属性来创建带参构造对象
<bean id="myStudent" class="com.Student">
<constructor-arg name="id" value="10"/>
<constructor-arg name="name" value="张三"/>
<constructor-arg name="school" ref="mySchool"/>
</bean>
- –使用index属性来创建带参构造对象
<bean id="myStudent" class="com.Student">
<constructor-arg index = "0" value="10"/>
<constructor-arg index = "1" value="张三"/>
<constructor-arg index = "2" ref="mySchool"/>
</bean>
- –省略index–顺序不能乱,与参数列表顺序一致
<bean id="myStudent" class="com.Student">
<constructor-arg value="10"/>
<constructor-arg value="张三"/>
<constructor-arg ref="mySchool"/>
</bean>
2. 基于注解的DI
di的语法分类:
- set注入(设置注入):spring调用的set方法,在set方法可以实现属性的赋值(80%)
- 构造注入,spring调用类的有参构造方来创建对象,在构造方法中完成赋值