Spring学习笔记
1、Spring
1.1、简介
-
Spring:春天------>给软件行业带来了春天!
-
2002,首次推出Spring框架的雏形:interface21框架!
-
spring框架以interface21框架为基础,经过不断重新设计,并不断丰富其内涵,于2004年3月24号发布了1.0正式版
-
Rod Johnson , SpringFramework创建人
-
Spring理念,使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2 + Spring + Hibernate!
-
SSM:SpringMVC + Spring + MyBatis!
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.2、优点
- Spring是一款开源的免费框架(容器)!
- Spring是一款经量级、非入侵式的框架!
- 控制反转(IOC),面向切面编程(AOP)!
- 支持事务的处理,对框架整合的支持
总结一句话!Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的开源框架!
1.3、组成

1.4、扩展
在Spring的官网有这个介绍:现代化的Java开发,说白就是基于Spring的开发!
- SpringBoot (Build Anyting 构建一切)
- 一个快速开发的脚手架
- 基于SpringBoot可以快速的开发单个微服务
- 约定大于配置
- SpringCloud (Coordinate Anyting 协调一切)
- SpringCloud是基于SpringBoot实现的
- SpringCloud Data Flow (Connect Everything 连接一切)
因为现在大部分公司都在使用SpringBoot在进行快速开发,学习SpringBoot的前提是要完全掌握Spring及SpringMVC。承上启下的作用。
弊端:发展得太久了以后,违背了原来的理念!配置十分繁锁,人称:“配置地狱!”
2、IOC理论推导
- UserDao接口
- UserDaoImpl实现类
- UserService业务接口
- UserServiceImpl 业务实现类
在我们之前的业务,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改代码。如果程序代码量十分大,修改一次的成本代价十分昂贵

我们使用一个Set接口实现,已经发生革命性的变化!
private UserDao userDao;
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序员手上
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象
这种思想,从本质上解决了问题,程序员不需要管理对象的创建。系统的耦合性大大降低,可以更加专注在业务的实现。
3、HelloSpring
所谓IOC,就是用Spring来创建、管理、装配对象!
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring中,这些都称为对象-->
<bean id="hello" class="com.zhang.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
4、IOC创建对象的方式
-
使用无参构造创建对象,默认!
-
假设需要使用有参构造赋值
-
下标赋值
<bean name="User" class="com.zhang.pojo.User"> <!--第一种,下标赋值--> <constructor-arg index="0" value="张"/> </bean> -
类型
<bean name="User" class="com.zhang.pojo.User"> <!--第二种,通过类型创建,不建议使用--> <constructor-arg type="java.lang.String" value="张三"/> </bean> -
name
<bean name="User" class="com.zhang.pojo.User"> <!--第三种,直接通过参数名来设置--> <constructor-arg name="name" value="李四"/> </bean>
-
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
5、Spring配置
5.1、别名
<alias name="User" alias="UserA"/>
5.2、Bean配置
<!--
id : bean的唯一标识符,也就是相当于我们的对象名
class : bean对象所对应的全限定名:包名 + 类名
name : 也是别名,name比alias更高级,可以取多个别名(逗号、空格、分号分割)
-->
<bean id="UserT" name="UserT,User3" class="com.zhang.pojo.UserT">
</bean>
5.3、import
这个import,一般用于团队开发,可以将多个配置文件,合并成一个
假设,现在有三个人同时开发,每个负责的类不同,不同的类注册在不同的bean中,我们可以利用import将所有人的beans.xml合并成一个总的
-
张三
-
李四
-
王五
-
applicationContext.xml
<import resource="beans.xml"/> <import resource="beans2.xml"/> <import resource="beans3.xml"/>
使用的时候,直接使用总的配置就可以了
6、依赖注入
6.1、构造器注入
前面已经说过了
6.2、Set方式注入【重点】
-
依赖注入: Set注入!
-
依赖:bean对象的创建依赖于容器
-
注入:bean对象中的所有属性,由容器注入!
-
【环境搭建】
-
复杂类型
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } -
真实测试对象
public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String, String> card; private Set<String> games; private String wife; private Properties info; } -
beans.xml
<bean id="student" class="com.zhang.pojo.Student"> <property name="name" value="张"/> <!--String--> <property name="address" ref="address"/> <!--String[]--> <property name="books"> <array> <value>红楼梦</value> <value>水浒传</value> <value>西游记</value> <value>三国演义</value> </array> </property> <!--list--> <property name="hobbys"> <list> <value>篮球</value> <value>羽毛球</value> </list> </property> <!--map--> <property name="card"> <map> <entry key="身份证" value="430165165165"/> <entry key="银行卡" value="34232523"/> </map> </property> <!--set--> <property name="games"> <set> <value>三国杀</value> <value>骑马与砍杀 </value> </set> </property> <!--null--> <property name="wife"> <null/> </property> <!--properties--> <property name="info"> <props> <prop key="学号">684815</prop> <prop key="班级">91</prop> </props> </property> </bean> <bean id="address" class="com.zhang.pojo.Address"> <property name="address" value="湘潭"/> </bean>
6.3、拓展方式注入
我可以的通过p命名空间或c命名空间注入
官网解释

使用:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间的注入,可以直接注入属性的值:property-->
<bean id="user" class="com.zhang.pojo.User" p:name="张三" p:age="18"></bean>
<!--c命令空间注入,可以通过构造器注入属性的值constructs-args-->
<bean id="user2" class="com.zhang.pojo.User" c:name="李四" c:age="19"></bean>
</beans>
注意点:c命名与p命名不能直接使用,需要导入约束
6.4、bean的作用域

-
单例模式(singleton)
<bean id="user2" class="com.zhang.pojo.User" c:name="李四" c:age="19" scope="singleton"></bean> -
原型模式(prototype),每次从容器中get时,都会产生一个新对象
<bean id="user2" class="com.zhang.pojo.User" c:name="李四" c:age="19" scope="prototype"></bean> -
其余的request、session、application、这些只在Web开发中使用到
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会自动在上下文寻找,并自动给bean装配属性
在Spring有三种装配方式
- 在xml中显示的配置
- 在Java中显示的配置
- 隐式的自动装配Bean【重要】
7.1、测试
环境搭建:一个人有两个宠物
7.2、ByName自动装配
<!--byName,会自动在容器上下文中查找,查找对象set后面的值对应beanIid-->
<bean id="people" class="com.zhang.pojo.People" autowire="byName">
<property name="name" value="张三"/>
</bean>
7.3、ByType自动装配
<!--byType,会自动在容器上下文中查找,查找对象相同类型beanIid
-->
<bean id="people" class="com.zhang.pojo.People" autowire="byType">
<property name="name" value="张三"/>
</bean>
小结
- byname时,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性set方法值一致
- bytype时,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致
7.4、使用注解实现自动
jdk1.5支持的注解,Spring2.5支持
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
要使用注解须知
-
导入须知
-
配置注解的支持
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>@Autowired
一般写在属性名上面,也可写在set方法上
Autowired是通过反射实现的,set方法可不要,前提是这个自动装配属性在IOC容器中存在,且符合名字byname
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为Null
public @interface Autowired {
boolean required() default true;
}
测试代码
public class People {
//如果显示定义了Autowired的required属性为false,则说明这个对象可以空,否则不行
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
如果@Autowired自动装配环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,可以使用【@Qualifier(value = "XXX")】配合【@Autowired】使用,指定一个唯一的bean注入。
@Autowired(required = false)
private Cat cat;
@Autowired
@Qualifier(value = "dog3333")
private Dog dog;
private String name;
@Resource注解
public class People {
@Resource
private Cat cat;
@Resource
private Dog dog;
private String name;
小结:
@Resource和@Autowired的区别
- 都是用来自动装配的,设置在属性的上面
- @Autowired通过bytype方式实现,而且必须要求这个对象存在【常用】
- @Resource 默认通过byname方式实现,byname找不到时,用bytype实现,两个都找不到,则报错【常用】
- 执行顺序不同@Resource 默认通过byname方式实现,@Autowired默认通过bytype方式实现
8、注解开发
在Spring4之后,要使用注解开发,需要保证aop的包导入了

使用注解需要导入context的约束,增加注解的支持
-
bean
-
属性如何注入
@Component public class User { //等价于 <property name="name" value="张三"/> @Value("张三1") public String name; } -
衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按三级分类!
-
dao 【@Repostiory】
-
service 【@Service】
-
controller【@Controller】
这个四个注解功能都一样的,都代表某个类注册到Spring中,装配Bean
-
-
自动装配置
- @Autowired 自动装配通过类型,名字 - @Nullable 字段标记了这个注解,说明这个字段可以为Null - @Resource 自动装配通过名字,类型 -
作用域
@Component @Scope("signleton") public class User { //等价于 <property name="name" value="张三"/> @Value("张三1") public String name; } -
小结
Xml与注解
- Xml更加万能,适用于任何场合,维护相对简单
- 注解不是自己的类使用不了,维护相对复杂
Xml与注解最佳实践
-
Xml负责管理bean
-
注解负责注入属性
-
在使用过程,要使注解生效,需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.zhang"/> <context:annotation-config/>
9、使用Java的方式配置Spring
完成不需要使用Spring的Xml配置,全权交给Java处理
JavaConfig是Spring的一个子项目,在Spring4之后,它成为一个核心功能
ClassPathXmlApplicationContext
AnnotationConfigApplicationContext
实体类
//这个注解的意思是代表这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("张324") //属性注入值
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
配置文件
import com.zhang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
// 这个也会被Spring容器托管,注册到容器中,因为它本身就是一个Component
// @Configuration代表这是一个配置类,就是beans.xml一样
@Configuration
@ComponentScan("com.zhang.pojo")
@Import(ZhangConfig1.class)
public class ZhangConfig {
//注册一个Bean,就相当于之前在配置文件写的一个bean标签
//这个方法的方法名,相当于bean标签中的id属性
//返回值相当于bean标签的Class属性
@Bean
public User getUser(){
return new User();
}
}
测试类
public static void main(String[] args) {
//如果完全使用配置类的方式去做,就只能通过AnnotationConfig上下文来获取对象,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(ZhangConfig.class);
User getUser = (User) context.getBean("user");
System.out.println(getUser.getName());
}
这种纯Java的配置方式,在Spring中随处可见
10、代理模式

10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,会做一些附属操作
- 客户:访问代理对象的人
代码分析:
-
接口
public interface Rent { abstract void rent(); } -
真实角色
public class Host implements Rent{ public Host() { super(); } @Override public void rent() { System.out.println("房东有房出租"); } } -
代理角色
public class Proxy implements Rent{ private Host host; public Proxy(){ } public Proxy(Host host) { this.host = host; } @Override public void rent(){ seeHost(); host.rent(); contract(); fare(); } //中介带看房子 public void seeHost(){ System.out.println("带看房子"); } public void contract(){ System.out.println("签订租赁合同"); } public void fare(){ System.out.println("收中介费"); } } -
客户端访问代理角色
public static void main(String[] args) { //房东要租房子 Host host = new Host(); //代理,中介帮房东租房子,但是呢?代理角色一般有附属操作 Proxy proxy = new Proxy(host); //不用面对房东,直接找中介 proxy.rent(); }
代理模式的好处:
- 可以使真实角色更加纯粹,不用关心公共的业务
- 公共也就交给了代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍开发效率会变低
10.2、加深理解

10.3、动态代理
- 动态代理和静态代理角色一样
- 动态代理的类是动态生成的,不是写好的
- 动态代理分为两大类,通过接口的动态代理,基于类的动态代理
- 基于接口 ---JDK动态代理【使用这个】
- 基于类---cglib
- java字节码实现 :javasist
需要了解两个类:Proxy:代理, InvocationHandler
动态代理的好处:
- 可以使真实角色更加纯粹,不用关心公共的业务
- 公共也就交给了代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类是一个接口,一般就是对应一类业务
- 一个动态代理可以代理多个类,只要是实现了同一个接口即可
源码在spring-08-proxy demo4
11、AOP
11.3使用Spring实现AOP
【重点】使用AOP织入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一:使用Spring的API接口【主要SpringAPI接口实现】
方式二:使用自定义实现AOP【主要是切面定义】
12、整合Mybatis
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关的
- aop织入
- mybatis-config【new】
-
编写配置文件
-
测试
12.1、回忆mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper
12.2、Mybatis-spring
- 编写数据源
- sqlSessionFactory
- sqlSessionTemplate
- 需要给接口加实现类
- 将自己写的实现类,注册到bean中
- 测试使用
13、声明式事务
1、回顾事务
- 把一组业务当成一个业务来做,要么都成功,要么都失败
- 事务在项目的开发中,十分重要,涉及到数据的一致性问题,不能马虎
- 确保完整性和一致性
事务ACID原则
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,不管系统发生什么问题,结果都不会被影响,被持久化的写入到存储器中

浙公网安备 33010602011771号