Spring
1、Spring介绍
1.1 简介
-
Spring理念:
使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2 + Spring + Hibernate!
-
SSM:SpringMVC + Spring + Mybatis!
官网:https://spring.io/projects/spring-framework#learn
官方下载地址:http://repo.spring.io/release/org/springframework/spring
GitHub:https://github.com/spring-projects/spring-framework
Maven依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jabc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.2 优点
- Spring是一个开源的免费的框架(容器)!
- Spring是一个轻量级的,非入侵式的框架!
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持!
总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
1.3 组成
-
Spring Core:Inversion of Control
Core模块是Spring的核心类库,Spring的所有功能都依赖于该类库,Core主要实现IOC功能,Spring的所有功能都是借助IOC实现的。
-
AOP:Aspect Oriented Programming
AOP模块是Spring的AOP库,提供了AOP(拦截器)机制,并提供常用的拦截器,供用户自定义和配置。
-
ORM:Object/Relation Mapping
Spring 的ORM模块提供对常用的ORM框架的管理和辅助支持,Spring支持常用的Hibernate,ibtas,jdao等框架的支持,Spring本身并不对ORM进行实现,仅对常见的ORM框架进行封装,并对其进行管理。
-
DAO模块
Spring 提供对JDBC的支持,对JDBC进行封装,允许JDBC使用Spring资源,并能统一管理JDBC事物,并不对JDBC进行实现。
-
WEB模块
WEB模块提供对常见框架如Struts1,WEBWORK(Struts 2),JSF的支持,Spring能够管理这些框架,将Spring的资源注入给框架,也能在这些框架的前后插入拦截器。
-
Context模块
Context模块提供框架式的Bean访问方式,其他程序可以通过Context访问Spring的Bean资源,相当于资源注入。 -
MVC模块
WEB MVC模块为Spring提供了一套轻量级的MVC实现,在Spring的开发中,我们既可以用Struts也可以用Spring自己的MVC框架,相对于Struts,Spring自己的MVC框架更加简洁和方便。
1.4 拓展
- Spring Boot
- 一个快速开发的脚手架。
- 基于Spring Boot可以快速的开发单个微服务。
- 约定大于配置!
- Spring Cloud
- Spring Cloud是基于Spring Boot实现的。
现在大多数公司都在使用Spring Boot进行快速开发,学习Spring Boot的前提,需要完全掌握Spring和SpringMVC!
弊端:发展了太久之后,为别来原来的理念,配置十分繁琐,人称“配置地狱”。
2、IOC理论推导
以前:
- UserDao 接口
- UserDaoImpl 实现类
- UserService 业务接口
- UserServiceImpl 业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个Set接口实现,已经发生了革命性的变化!
private UserDao userDao;
// 利用Set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前:程序是主动创建对象,控制权在程序员受上!
- 使用Set注入后:程序不再具有主动性,而是变成了被动得接受对象!
这种思想,从本质上解决了问题,我们程序员不用再去管理对象得创建了,系统的耦合性大大降低,可以更加专注在业务得实现上,这是IOC得原型!
IOC本质
控制反转(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法。也有人人为DI只是IOC的另一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection,DI)。
3、HelloSpring
- 创建实体类
package com.cheng.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 + '\'' +
'}';
}
}
- 配置文件
<?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
原来:
类型 变量名 = new 类型();
Hello hello = new Hello();
现在:
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.cheng.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
- 测试
import com.cheng.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
// 获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
思考问题?
-
Hello对象是谁创建的?
hello 对象是由Spring创建的
-
Hello 对象的属性是怎么设置的?
hello 对象的属性是由Spring容器设置的。
这个过程就叫控制反转:
控制:是来控制对象的创建,传统应用程序的对象是有程序本身控制创建的,使用Spring后,对象是由Spring创建的。
反转:程序本身不创建对象,而变成被动的接收对象。
依赖注入:就是利用set方法来进行注入的。
IOC是一种编程思想,由主动的编程编程变成被动的接收。
可以通过 new ClassPathXmlApplicationContext 去浏览一下底层源码。
到了现在,我们彻底不用再去程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!
4、IOC创建对象的方式
-
使用无参构造创建对象,默认!
-
假设我们要使用有参构造创建对象
-
下标赋值
<!--有参构造,第一种方式:通过下标赋值--> <bean id="User" class="com.cheng.pojo.User"> <constructor-arg index="0" value="张三"/> </bean>
-
类型
<!--有参构造,第二种方式:通过类型创建,不建议使用--> <bean id="User" class="com.cheng.pojo.User"> <constructor-arg type="java.lang.String" value="张三"/> </bean>
-
通过参数名
<!--有参构造,第三种方式:直接通过参数名--> <bean id="User" class="com.cheng.pojo.User"> <constructor-arg name="name" value="张三"/> </bean>
-
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
5.Spring配置
5.1 别名
<!--alias:别名
如果添加了别名,我们也可以通过别名获取到这个对象
-->
<alias name="User" alias="newUser"/>
5.2 Bean 的配置
<!--有参构造,第三种方式:直接通过参数名-->
<!--
id : bean 的唯一标识符,也就是相当于我们学的对象名
class : bean 对象所对应的全限定名 : 包名 + 类名
name : 也是别名,可以同时取多个别名,用空格或逗号隔开
-->
<bean id="User" class="com.cheng.pojo.User" name="user, user2 user3; user4">
<constructor-arg name="name" value="张三"/>
</bean>
5.3 import
这个import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个。
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的 bean 中,我们可以利用 import 将所有人的 beans.xml 合并为一个总的!
-
beans1.xml
-
beans2.xml
-
beans3.xml
-
applicationContext.xml(总的)
<import resource="beans1.xml"/> <import resource="beans2.xml"/> <import resource="beans3.xml"/>
使用的时候,直接使用总的配置就可以了。
6、DI(依赖注入)
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; } @Override public String toString() { return "Address{" + "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; // get/set/toString方法略…… }
-
beans.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="address" class="com.cheng.pojo.Address"> <property name="address" value="地球村"/> </bean> <bean id="student" class="com.cheng.pojo.Student"> <!--第一种:普通值注入,value--> <property name="name" value="张三"/> <!--第二种:bean注入,ref--> <property name="address" ref="address"/> <!--第三种:数组注入,array--> <property name="books"> <array> <value>Java入门手册</value> <value>Python入门手册</value> <value>C语言入门手册</value> <value>PHP入门手册</value> <value>Linux入门手册</value> </array> </property> <!--第四种:List集合,list--> <property name="hobbys"> <list> <value>学Java</value> <value>学Python</value> <value>学PHP</value> <value>学Linux</value> </list> </property> <!--第五种:Map集合,map--> <property name="card"> <map> <entry key="学生证" value="ID123456"/> <entry key="借书证" value="ID654321"/> </map> </property> <!--第六种:Set集合,set--> <property name="games"> <set> <value>飞花令</value> <value>成语接龙</value> <value>数独</value> </set> </property> <!--第七种:null--> <property name="wife"> <null/> </property> <!--第八种:Properties: prop key=value--> <property name="info"> <props> <prop key="性别">男</prop> <prop key="身高">180</prop> <prop key="体重">160</prop> </props> </property> </bean> </beans>
-
测试类
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); }
测试结果
Student{ name='张三', address=Address{address='地球村'}, books=[Java入门手册, Python入门手册, C语言入门手册, PHP入门手册, Linux入门手册], hobbys=[学Java, 学Python, 学PHP, 学Linux], card={学生证=ID123456, 借书证=ID654321}, games=[飞花令, 成语接龙, 数独], wife='null', info={体重=160, 身高=180, 性别=男} }
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.cheng.pojo.User" p:name="张三" p:age="20"/>
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.cheng.pojo.User" c:age="18" c:name="李四"/>
</beans>
测试
// p命名空间
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
// c命名空间
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"
-
c命名空间通过构造器注入,使用时需要生成有参构造方法
6.4 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 . |
-
单例模式(Spring默认机制)
<bean id="user" class="com.cheng.pojo.User" p:name="张三" p:age="20" scope="singleton"/>
-
原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="user2" class="com.cheng.pojo.User" c:age="18" c:name="李四" scope="prototype"/>
-
其余的request、session、application,这些个只能在web中使用到!
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式!
- spring会在上下文中自动寻找,并自动给bean装备配属性
在Spring中有三种装配方式:
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配bean【重要】
7.1 测试
public class Cat {
public void shout() {
System.out.println("喵~~~");
}
}
public class Dog {
public void shout() {
System.out.println("汪~~~");
}
}
public class People {
private String name;
private Cat cat;
private Dog dog;
// ……
}
<bean id="cat" class="com.cheng.pojo.Cat"/>
<bean id="dog" class="com.cheng.pojo.Dog"/>
<bean id="people" class="com.cheng.pojo.People">
<property name="name" value="张三"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
7.2 byName自动装配
<bean id="cat" class="com.cheng.pojo.Cat"/>
<bean id="dog" class="com.cheng.pojo.Dog"/>
<!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值相对应的 beanid-->
<bean id="people" class="com.cheng.pojo.People" autowire="byName">
<property name="name" value="张三"/>
</bean>
7.3 byType自动装配
<bean class="com.cheng.pojo.Cat"/>
<bean class="com.cheng.pojo.Dog"/>
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的 bean,需要保证类型全局唯一
-->
<bean id="people" class="com.cheng.pojo.People" autowire="byType">
<property name="name" value="张三"/>
</bean>
小结:
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
- byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
7.4 使用注解实现自动装配
jdk 1.5 支持的注解,Spring 2.5 支持注解。
要使用注解须知:
-
导入约束
xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
-
配置注解的支持: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/>
@Autowired
- 直接在属性上使用即可,也可以在set方式上使用
- 使用@Autowired我们可以不用编写set方法,前提是你这个自动装配的属性在IOC容器中存在,且符合名字byname!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
代码示范
public class People {
// 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不可以为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
public void setDog(@Nullable Dog dog) {
this.dog = dog;
}
// ……
}
如果 @Autowired 自动装配环境比较复杂,自动装配无法通过一个注解 @Autowired 完成的时候,我们可以使用 @Qualifier(value = “xxx”) 去配置 @Autowired 的使用,指定一个唯一的 bean 对象注入!
public class People {
@Autowired
@Qualifier(value = "cat23")
private Cat cat;
@Autowired
@Qualifier(value = "dog45")
private Dog dog;
private String name;
}
@Resource注解
关于Spring不能引入@Resource的问题
-
JDK11以后完全移除了javax扩展,所以不能使用@resource注解。
解决方案:
通过maven引入依赖<dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency>
然后导包使用即可。
代码示例:
import javax.annotation.Resource; public class People { @Resource(name = "cat23") private Cat cat; @Resource private Dog dog; private String name; }
8、使用注解开发
-
在Spring4之后,要使用注解开发,必须要保证 aop 的包导入了
<!--导入spring-webmvc依赖就会自动下载包括 aop 在内的包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
-
使用注解需要导入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:component-scan base-package="com.cheng.pojo"/> <context:annotation-config/> </beans>
8.1 bean
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean
// Component : 组件 相当于<bean id="user" class="com.cheng.pojo.User"/>
@Component
public class User {
}
8.2 属性如何注入
@Component
public class User {
// 相当于 <property name="name" value="法外狂徒张三"/>
@Value("法外狂徒张三")
public String name;
}
8.3 衍生的注解
@Component 有几个衍生注解,我们在 web 开发中,会按照 MVC 三层架构分层!
- dao ==> @Repository
- service ==> @Service
- controller ==> @Controller
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配 bean
8.4 自动装配
-
@Autowired 自动装配,通过类型,名字
如果 @Autowired 不能唯一自动装配上属性,则需要通过 @Qualifier(value = “xxx”)
-
@Nullable 字段标记了这个注解,说明这个字段可以为null
-
@Resource 自动装配,通过名字,类型
8.5 作用域
@Scope 可以设置值
@Component
@Scope("prototype")
public class User {
// 相当于 <property name="name" value="法外狂徒张三"/>
@Value("法外狂徒张三")
public String name;
}
8.6 小结
xml 与 注解:
- xml 更加万能,使用与任何场合,维护简单方便;
- 注解 不是自己的类使用不了,维护相对复杂;
xml 与 注解 最佳实践:
-
xml 用来管理 bean;
-
注解值负责完成属性的注入 ;
-
我们在使用的过程中,只需要注意一个问题:必须要让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.cheng"/> <context:annotation-config/>
9、使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig 是 Spring 的一个子项目,在 Spring4 之后,它成为了一个核心功能!
实体类
public class User {
@Value("法外狂徒张三")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
// 这个也会被Spring容器托管,注册到容器中
@Configuration
@ComponentScan("com.cheng.pojo")
@Import(ChengConfig02.class)
public class ChengConfig {
// 注册一个Bean,就相当于之前写的一个bean标签
// 这个方法的名字,就相当于bean标签中的id属性
// 这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser() {
return new User();// 就是返回要注入到bean的对象
}
}
测试
@Test
public void configTest() {
// 如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(ChengConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
这种纯Java的配置方式,在SpringBoot中随处可见!
10 代理模式
为什么要学习代理模式?
因为这就是 SpringAOP 的底层!
代理模式的分类:
- 静态代理
- 动态代理
10.1 静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
-
接口
public interface Rent { public void rent(); }
-
真实角色
public class Host implements Rent{ public void rent() { System.out.println("房东:我有房子要出租🏠"); } }
-
代理角色
public class Proxy implements Rent { private Host host; public Proxy() { } public Proxy(Host host) { this.host = host; } public void rent() { host.rent(); see(); contract(); check(); } private void see() { System.out.println("黑中介:我先带你看房👀"); } private void contract() { System.out.println("黑中介:看好房去签合同✍"); } private void check() { System.out.println("黑中介:签完合同,没事别来烦我,有事你肯定找不到我😼"); } }
-
客户端访问代理角色
public static void main(String[] args) { Proxy proxy = new Proxy(new Host()); proxy.rent(); }
代理模式的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共业务就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会降低
10.2 动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类
- 基于接口的动态代理:最经典的就是JDK动态代理
- 基于类的动态代理:cglib
- Java字节码实现:javassist
需要了解两个类
- Proxy:代理
- InvocationHandler:调用处理程序
具体代码:
接口
public interface Mysql {
public void add();
public void delete();
public void update();
public void select();
}
接口实现类
public class MysqlImpl implements Mysql {
public void add() {
System.out.println("add");
}
public void delete() {
System.out.println("delete");
}
public void update() {
System.out.println("update");
}
public void select() {
System.out.println("select");
}
}
自动生成代理类的类
package com.cheng.demo04;
import com.cheng.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
// 生成得到代理类
public Object getProxy() {
return Proxy.newProxyInstance(
this.getClass().getClassLoader(),// 获得类加载器
target.getClass().getInterfaces(),// 获得需要代理的接口
this);
}
// 处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());// 调用日志方法,可以去掉
Object result = method.invoke(target, args);
return result;
}
// 日志方法,可以去掉
public void log(String msg) {
System.out.println("即将调用"+ msg +"方法:");
}
}
测试
public static void main(String[] args) {
// 真实对象
MysqlImpl mysqlImpl = new MysqlImpl();
// 代理角色 : 现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
// 通过调用程序处理角色来处理我们要调用的接口对象
pih.setTarget(mysqlImpl);
Mysql proxy = (Mysql) pih.getProxy();// 这里的proxy就是动态生成的
proxy.add();
}
动态代理的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共业务就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
11 AOP
11.1 什么是AOP?
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术,AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2 AOP 在 Spring 中的作用
提供声明式事务,允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点,如日志,安全,缓存,事务等等。
- 切面(Aspect):横切关注点 被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法
- 目标(Target):被通知对象
- 代理(Proxy):向目标对象应用通知之后创建的对象
- 切入点(PointCut):切面通知 执行的“地点”的定义
- 连接点(JointPoint):与切入点匹配的执行点
springAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
通知类型 | 连接点 | 实现接口 |
---|---|---|
前置通知 | 方法前 | org.springframework.aop.MethodBeforeAdvice; |
后置通知 | 方法后 | org.springframework.aop.AfterReturningAdvice; |
环绕通知 | 方法前后 | org.aopalliance.intercept.MethodInterceptor; |
异常抛出通知 | 方法抛出异常 | org.springframework.aop.ThrowsAdvice; |
引介通知 | 类中增加新的方法属性 | org.springframework.aop.IntroductionInterceptor; |
即 AOP 在不改变原有代码的情况下,去增加新的功能。
11.3 使用Spring实现AOP
【重点】使用AOP植入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
测试实例:
接口
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
接口实现类
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("add:增加了一个用户");
}
public void delete() {
System.out.println("delete:删除了一个用户");
}
public void update() {
System.out.println("update:修改了一个用户");
}
public void select() {
System.out.println("select:查询了一个用户");
}
}
方式一:使用Spring的API接口【主要是 Spring API 接口实现】
Spring API接口实现
package com.cheng.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
// method:要执行的目标对象的方法
// args:参数
// target :目标对象
// returnValue : 返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + "的" + method.getName() + "方法,返回值为:" + returnValue);
}
}
package com.cheng.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class BeforLog implements MethodBeforeAdvice {
// method:要执行的目标对象的方法
// args:参数
// target :目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + "的" + method.getName() + "方法即将被执行……");
}
}
配置
<!--注册bean-->
<bean id="UserServiceImpl" class="com.cheng.service.UserServiceImpl"/>
<bean id="BeforLog" class="com.cheng.log.BeforLog"/>
<bean id="AfterLog" class="com.cheng.log.AfterLog"/>
<!--方式一:使用原生的 Spring API接口-->
<!--配置aop:需要导入 aop 的约束-->
<aop:config>
<!--切入点 expression()表达式:execution( )-->
<aop:pointcut id="pointcut" expression="execution(* com.cheng.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="BeforLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
</aop:config>
测试
@Test
public void LogTest() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 动态代理代理的是接口
UserService userService = (UserService) context.getBean("UserServiceImpl");
userService.add();
}
方式二:自定义类来实现AOP【主要是切面定义】
自定义切面
public class DiyPointcut {
public void befor() {
System.out.println("============方法即将开始===========");
}
public void after() {
System.out.println("============方法执行结束===========");
}
}
配置
<!--注册bean-->
<bean id="UserServiceImpl" class="com.cheng.service.UserServiceImpl"/>
<bean id="diyPointcut" class="com.cheng.DiyLog.DiyPointcut"/>
<!--方法二:自定义类-->
<aop:config>
<!--自定义切面 ref 要引用的类-->
<aop:aspect ref="diyPointcut">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.cheng.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="befor" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
测试不变!
方式三:使用注解实现
package com.cheng.DiyLog;
// 方式三:使用注解实现
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect // 标注这个类是一个切面
public class AnnotationPointcut {
@Before("execution(* com.cheng.service.UserServiceImpl.*(..))")
public void annotationBefor() {
System.out.println("annotation:方法即将开始……");
}
@After("execution(* com.cheng.service.UserServiceImpl.*(..))")
public void annotationAfter() {
System.out.println("annotation:方法已经结束!");
}
@Around("execution(* com.cheng.service.UserServiceImpl.*(..))")
public void annotationAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前……");
Signature signature = pjp.getSignature();// 获得签名
System.out.println(signature);
Object proceed = pjp.proceed();// 执行方法
System.out.println("环绕后……");
System.out.println(proceed);
}
}
配置
<!--注册bean-->
<bean id="UserServiceImpl" class="com.cheng.service.UserServiceImpl"/>
<!--方法三:使用注解-->
<bean id="AnnotationPointcut" class="com.cheng.DiyLog.AnnotationPointcut"/>
<!--开启注解支持
默认JDK:proxy-target-class="false"
cglib:proxy-target-class="true"
-->
<aop:aspectj-autoproxy/>
测试结果
环绕前……
void com.cheng.service.UserService.add()
annotation:方法即将开始……
add:增加了一个用户
环绕后……
null
annotation:方法已经结束!
12、整合Mybatis
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关的
- aop植入
- mybatis-spring
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <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.4.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.4</version> </dependency> <!--偷懒包,非必要--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
-
编写配置文件
-
测试
12.1 回忆mybatis
-
编写实体类
User
package com.cheng.pojo; import lombok.Data; @Data public class User { private int id; private String name; private String pwd; }
-
编写核心配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--核心配置文件--> <configuration> <typeAliases> <package name="com.cheng.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
-
编写接口
UserMapper
package com.cheng.mapper; import com.cheng.pojo.User; import java.util.List; public interface UserMapper { public List<User> selectUser(); }
-
编写UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cheng.mapper.UserMapper"> <select id="selectUser" resultType="user"> select * from mybatis.user; </select> </mapper>
在配置文件中注册
<mappers> <mapper class="com.cheng.mapper.UserMapper"/> </mappers>
-
测试
import com.cheng.mapper.UserMapper; import com.cheng.pojo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MyTest { @Test public void selectTest() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); for (User user : users) { System.out.println(user); } sqlSession.close(); } }
附:资源导入失败解决方案
在pom.xml中配置
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
12.2 mybatis-spring
准备工作:
-
在pom.xml中配置
<!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
-
实体类:User
-
接口:UserMapper
-
配置:UserMapper.xml
-
配置:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--核心配置文件--> <configuration> <typeAliases> <package name="com.cheng.pojo"/> </typeAliases> </configuration>
-
编写数据源配置
-
sqlSessionFactory
-
sqlSessionTemplate
spring-mapper.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"> <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3po dbcp druid 我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource --> <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?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"/> <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="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/cheng/mapper/*.xml"/> </bean> <!--SqlSessionTemplate:就是我们使用的sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入sqlSessionFactory,因为它没有没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> </beans>
-
需要给接口加实现类
方式一:
UserMapperImpl
package com.cheng.mapper; import com.cheng.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; public class UserMapperImpl implements UserMapper { // 原来,我们的所有操作都使用sqlSession来执行 // 现在,我们使用SqlSessionTemplate private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } }
方式二:
UserMapperImpl2
package com.cheng.mapper; import com.cheng.pojo.User; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { public List<User> selectUser() { return getSqlSession().getMapper(UserMapper.class).selectUser(); } }
通过继承SqlSessionDaoSupport,可以省略第三步的内容,即省略 spring-mapper.xml 中的如下配置:
<!--SqlSessionTemplate:就是我们使用的sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入sqlSessionFactory,因为它没有没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
将自己写的实现类,注入到Spring中
applicationContext.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"> <import resource="spring-mapper.xml"/> <!--对应方式一--> <bean id="userMapper" class="com.cheng.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> <!--对应方式二--> <bean id="userMapper2" class="com.cheng.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
-
测试
对应方式一:
@Test public void selectTest() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> users = userMapper.selectUser(); for (User user : users) { System.out.println(user); } }
对应方式二:
@Test public void selectTest() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper2 userMapper = context.getBean("userMapper2", UserMapper2.class); List<User> users = userMapper.selectUser(); for (User user : users) { System.out.println(user); } }
13、声明式事务
13.1 回顾事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败;
- 事务在项目开发中十分重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性;
事务ACID原则:
-
原子性
-
一致性
-
隔离性
- 多个业务可能操作同一个资源,放置数据损坏
-
永久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中
13.2 spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理
具体实现:
注:基于以上代码进行修改
在spring-mapper.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3po dbcp druid
我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<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?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"/>
<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="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/cheng/mapper/*.xml"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- <constructor-arg ref="dataSource"/>-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知:-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性:propagation="REQUIRED"(默认)-->
<tx:attributes>
<tx:method name="insert" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="select" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointcat" expression="execution(* com.cheng.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcat"/>
</aop:config>
</beans>
测试不用修改!
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况;
- 如果我们不在spring中去配置声明式事务,我们就需要在代码中手动配置事务;
- 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!