Spring学习笔记
Spring
简介
spring理念:是现有的技术更加容易使用,本身是一个大杂烩。
- SSH:Struct2 + Spring + Hibernate
- SSM: SpringMVC + Spring + Mybatis
官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GitHub: https://github.com/spring-projects/spring-framework
Spring Web MVC » 5.2.5.RELEASE
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
- spring是开源的免费的容器。
- spring是一个轻量级的,非入侵式的。
- 控制反转(IOC),面向切面编程 (AOP)。
- 支持事务处理,对框架整合的支持。
总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。
组成
拓展
现代化java开发
-
Spring Boot
- 一个快速开发的手脚架
- 基于SpringBoot可以快速开发单个服务
- 约定大于配置
-
Spring Cloud
-
SpringCloud是基于SpringBoot实现的。
Spring SpringMVC SpringBoot
IOC理论
- UserDao
- UserDaoImp
- UserSevice
- UserServiceImp
在之前,用户的需求可能会影响原来的代码。
使用一个set。
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
- 之前是主动创建对象,控制权在程序员手上。
- 使用set之后,是被动接受对象。
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
IOC本质
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入(Dependency Injection,Dl)。
Hello Spring
package com.kuang.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
IOC创建对象的方式
1.使用无参构造创建对象,默认!
2.假设要使用有参构造创建对象。
1.下标赋值
<!-- 有参构造下标赋值-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg index="0" value="小王二"/>
</bean>
2.通过类型创建
<!-- 不建议使用,当有两个相同类型时无法判断-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg type="java.lang.String" value="小王三"/>
</bean>
3.参数名
<!-- 第三种直接通过参数名-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg name="name" value="小王四"/>
</bean>
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
Spring配置
别名alias
Bean的配置
<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的全限定名:包名+类名
name:别名 name可以同时取多个别名
-->
<bean id="userT" class="com.kuang.pojo.UserT" name="user2 u2,u3;u4">
<property name="name" value="小王五"/>
</bean>
import
一般用于团队开发,可以将多个配置文件导入合并为一个
使用applicationContext.xml即可
DI依赖注入
构造器注入
Set方式注入【重点】
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性由容器注入
【环境搭建】
1.复杂类型
package com.kuang.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试对象
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 Properties info;
private String wife;
}
3.bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.kuang.pojo.Student">
<!-- 普通值注入,value-->
<property name="name" value="小王六"/>
</bean>
</beans>
4测试类
public class Mytest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student.getName());
}
}
完善注入信息
<?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">
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="长沙"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!-- 普通值注入,value-->
<property name="name" value="小王六"/>
<!-- Bean注入,ref-->
<property name="address" ref="address"/>
<!-- 数组注入,ref-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!-- list-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>画画</value>
<value>吃饭</value>
</list>
</property>
<!-- Map-->
<property name="card">
<map>
<entry key="身份证" value="1234567812345678"/>
<entry key="银行卡" value="62222265652222"/>
</map>
</property>
<!-- Set-->
<property name="games">
<set>
<value>LOL</value>
<value>yjwj</value>
<value>jw3</value>
</set>
</property>
<!--null-->
<property name="wife" value=""/>
<!--Properties-->
<property name="info">
<props>
<prop key="学号">20210728</prop>
<prop key="性别">男</prop>
<prop key="姓名">小王七</prop>
</props>
</property>
</bean>
</beans>
拓展方式注入
我们可以使用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.kuang.pojo.User" p:name="小王" p:aeg="18"/>
<!-- c 命名空间注入 通过构造器注入:constructs-args-->
<bean id="user2" class="com.kuang.pojo.User" c:aeg="18" c:name="小王二"/>
</beans>
测试:
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
注意:
p命名和c命名空间不能直接使用需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
bean的作用域
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext . |
1.单例模式(Spring默认机制)
<bean id="user" class="com.kuang.pojo.User" p:name="小王" p:aeg="18" scope="singleton"/>
2.原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="user" class="com.kuang.pojo.User" p:name="小王" p:aeg="18" scope="prototype"/>
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user2", User.class);
System.out.println(user==user2); //false
System.out.println(user.hashCode());//1605851606
System.out.println(user2.hashCode());//1267556427
}
3.request、session、application、只能在web开发中使用
Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式
- Spring会在上下文中自动寻找,并给bean装配属性
三种自动装配
1.在xml中显示配置
2.在java中显示配置
3.隐式的自动装配bean【重要】
测试
环境搭建 一个人有两个宠物!
ByName自动装配
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byName">
<property name="name" value="小王三"/>
ByType自动装配
<?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">
<bean class="com.kuang.pojo.Cat"/>
<bean class="com.kuang.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
<property name="name" value="小王三"/>
</bean>
</beans>
小结:
byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
byType的时候需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
使用注解实现装配
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
使用注解须知
1.导入约束.context约束
2.配置注解的支持: context:annotation-config/
<?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(Spring)容器中存在,且符合名字byname
@Nullable 字段标记了这个注解,说明这个字段可以为null。
public @interface Autowired {
boolean required() default true;
}
public class People {
//如果显示定义了 Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
如果@Autowired自动装配环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时我们可以使用@Qualifier(value = "xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
小结
@Resource和Autowire的区别:
-
都是用来装配的都可以放在属性字段上
-
@Autowire通过byType的方式实现必须要求 这个对象存在
-
@Resource默认通过byName方式实现如果找不到名字则通过byType实现 如果两个都找不到就报错。
-
执行顺序不同:@Autowire通过byType的方式实现。@Resource默认通过byName方式实现。
使用注解开发
使用注解开发要保证aop包导入
使用注解要导入context约束增加注解支持
<?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>
bean
属性如何注入
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于 <bean id=“user” class="com.kuang.pojo.User"/>
//Component 组件
@Component
public class User {
public String name = "小王";
//等价于 <property name="name" value="王小二"/>
@Value("王小二")
public void setName(String name) {
this.name = name;
}
}
衍生的注解
- @Component有几个衍生注解,在web开发中按照mav三层架构分层
- dao【@Repository】
- service【@Service】
- controller【@Controller】
自动装配置
@Autowired :自动装配通过类型。名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
@Nullable字段标记了这个注解,说明这个字段可以为null;
@Resource :自动装配通过名字。类型。
作用域
@Scope("prototype")
小结
xml与注解
- xml更加万能,适用于任何场合!维护简单方便
- 注解 不是自己类使用不了,维护相对复杂
xml与注解的最佳实践:
- xml用来管理bean;
- 注解只负责注入属性;
- 在使用过程中需注意让注解生效,就需要开启注解的支持
<!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>
使用Java的方式配置Spring
JavaConfig是Spring的一个子项目,Spring4之后成为核心功能
实体类
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解的意思就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("小王")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
package com.kuang.config;
import com.kuang.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;
@Configuration
//这个也会被Spring容器托管注册到容器中因为他本来就是一个@Component。
// @Configuration代表这是一个配置类,等价于beans.XML
@ComponentScan("com.kuang.pojo")
@Import(WangConfig2.class)
public class WangConfig {
//注册一个Bean相当于之前写的一个Bean标签
//bean标签中的id属性,为方法名。
//这个方法的返回值为bean标签的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入bean的对象
}
}
测试类
public class MyTest {
public static void main(String[] args) {
//如果完全使用配置类方式,我们就只能通过AnnotationConfig上下文来获取容器通过配置类的class对象加载
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WangConfig.class);
User getUser = context.getBean("getUser", User.class);
System.out.println(getUser.getName());
}
}
代理模式
SpringAOP的底层【SpringAOP和SpringMVC】
代理模式的分类:
- 静态代理
- 动态代理
静态代理:
角色分析:
- 抽象角色:一般会使用接口或抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
-
接口
//租房 public interface Rent { public void rent(); }
-
真实角色
//房东 public class Host implements Rent{ @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() { seeHouse(); host.rent(); hetong(); fare(); } public void seeHouse(){ System.out.println("中介带你看房"); } public void hetong(){ System.out.println("签租赁合同"); } public void fare(){ System.out.println("收中介费"); } }
-
客户端访问代理角色
public class Client { public static void main(String[] args) { //房东需要出租房子 Host host = new Host(); //代理,中介帮房东出租房子。代理角色会有一些附属操作。 Proxy proxy = new Proxy(host); //你不用面对房东直接找中介租房即可 proxy.rent(); } }
静态代理模式的好处:
- 可以使真实角色的操作更加纯粹 不用关注一些公共业务
- 公共业务就交给代理角色实现了业务的分工
- 公共业务发生扩展的时候方便集中管理
缺点:
- 一个真实角色会产生一个代理角色;代码量翻倍开发效率变低。
动态代理
- 动态代理与静态代理角色一样
- 动态代理类是动态生产的不是我们直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口-JDK动态代理
- 基于类:cglib
- java字节码实现:JAVAssist
需要了解两个类:Proxy:代理、InvocationHandler:调用处理程序
动态代理模式的好处:
- 可以使真实角色的操作更加纯粹 不用关注一些公共业务
- 公共业务就交给代理角色实现了业务的分工
- 公共业务发生扩展的时候方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
AOP
什么是AOP
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
使用Spring实现AOP
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
方式一:使用Spring的API接口实现AOP【主要是Spring的API接口实现】
方式二:自定义类来实现AOP【主要是切面定义】
方式三:使用注解实现
整合Mybatis
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
- mybatis-spring
-
编写配置文件
-
测试
-
编写数据源配置
-
sqlSessionFactory
-
sqlSessionTemplate
-
给接口加实现类
-
将实现类注入Spring中
-
测试
声明式事务
回顾事务
- 把一组业务当成一个业务,要么都成功,要么都失败
- 确保数据的完整性和一致性问题
事务的ACID原则
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏。
- 持久性
- 事务一旦提交,无论系统发生什么问题结果都不会再被影响,被持久化写到存储器中。
Spring事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理。
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置
这里使用Spring提供的jdbc-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定Mybatis配置文件 -->
<property name="configLocation" value="mabatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate:就是SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="datasource" />
</bean>
<!--结合aop实现事务置入-->
<!--配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txpointCut" expression="execution(* com.kuang.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpointCut"/>
</aop:config>
</beans>
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致情况
- 如果不在Spring中配置事务就需要在代码中手动配置事务
- 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题