Spring框架
-
Spring框架最主要的作用就是为代码“解耦”,降低代码之间的耦合度,让对象和对象(模块和模块)之间的关系不是使用代码关联,而是通过配置来说明,即在Spring中说明对象(模块)的关系
-
Spring根据代码的功能特点,使用IOC降低业务对象之间的耦合度,IOC使得业务在相互调用的过程中不需要再自己维护关系了,即不用在自己创建使用的对象了,而AOP实现了系统服务最大程度上的复用
Spring概述
Spring的优点
-
轻量级:
-
由20多个模块构成,每一个jar包都很小,小于1M,核心包3M左右,对代码无污染
-
-
面向接口编程:
-
使用接口,项目的可扩展性,可维护性都极高,接口不关心实现类的类型,使用时接口指向实现类,切换实现类即可切换整个功能
-
-
AOP:面向切面编程
-
当程序中公共的、通用的、重复的部分被提取出来,单独开发,封装到一个模块(切面)中,在使用时,通过反织的方式来调用相对应的方法,就是面向切面编程,底层逻辑是动态代理
-
-
整合其他框架:
-
整合后使其他框架更易用
-
IOC
-
控制反转IoC是一个概念,是一种思想,由Spring容器进行对象的创建和依赖注入,在使用时可以直接取出使用
-
基于xml的IOC
-
创建对象(当容器启动时,自动创建对象)
-
//如果需要从spring容器中取出对象,则需要先创建容器对象,并启动才能够取出对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");//启动容器 Student stu = (Student) ac.getBean("stu"); System.out.println(stu);
-
<!--创建学生对象 <bean id="stu" class="com.wsh.pojo.Student"></bean> 等同于Student stu = new Student(); id:创建对象的名称 class:就是创建对象的类型,底层是通过反射来构建对象 只要容器被启动,则对象就会被创建--> <bean id="stu" class="com.wsh.pojo.Student"></bean>
-
-
给创建的对象赋值
-
使用setter注入
-
注入分为简单类型注入和引用类型注入(在bean工厂创建对象时,没有先后顺序之分)
-
简单类型注入值使用value属性
-
引用类型注入使用ref属性
-
<bean id="school" class="com.wsh.pojo2.School"> <property name="name" value="力行中学"></property> <property name="address" value="盐湖"></property> </bean> <bean id="stu" class="com.wsh.pojo2.Student"> <property name="name" value="张三"></property> <property name="age" value="12"></property> <!-- 依赖性注入--> <property name="school" ref="school"></property> </bean>
-
-
-
注意:使用setter方法注入时,必须提供无参的构造方法,必须提供set()方法
-
使用构造方法注入(简单类型和引用类型)
-
Student student = new Student("张三",22);
-
使用构造方法的参数名称进行注入
-
<!-- 创建学校对象并注入值--> <bean id="school" class="com.wsh.pojo3.School"> <constructor-arg name="name" value="力行中学"></constructor-arg> <constructor-arg name="address" value="盐湖"></constructor-arg> </bean>
-
使用构造方法参数的下标注入值
-
<!-- 创建学生对象并注入值,通过构造方法的参数下标来注入值--> <bean id="stu" class="com.wsh.pojo3.Student"> <constructor-arg index="0" value="张三"></constructor-arg> <constructor-arg index="1" value="12"></constructor-arg> <constructor-arg index="2" ref="school"/> </bean>
-
使用默认的构造方法的参数的顺序注入值
-
<!-- 创建学生对象并注入值,通过构造方法的参数默认顺序进行注入值--> <bean id="stuSequence" class="com.wsh.pojo3.Student"> <constructor-arg value="李四"></constructor-arg> <constructor-arg value="22"></constructor-arg> <constructor-arg ref="school"></constructor-arg> </bean>
-
-
-
注意:使用构造方法注入时在applicationConte
-