1、Spring
1.1、简介
-
Spring:春天–>给软件行业带来了春天
-
2002年首次提出了Spring框架的雏形:interface21框架!
-
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
-
Rod Johnson,Spring Framework的创始人,著名作者。很难想象Rod Johnson的学历,他是悉尼大学的博士,然而他的专业并不是计算机,而是音乐学。
-
Spring的理念:使现有的技术更加容易使用,本身就是一个大杂烩,整合了现有的的技术框架!
-
SSH:Structs2+Spring+Hibernate
-
SSM:Spring+SpringMVC+Mybatis
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.15</version>
</dependency>
1.2、优点
- Spring是一个开源的免费的框架(容器)!
- Spring是一个轻量级、非入侵式的框架!
- 控制反转(IOC)、面向切面编程(AOP)
- 支持事务处理,对框架整合的支持!
- 总结:Spring就是一个轻量级的控制反转(IOC),和面向切面编程的框架!
1.3、Spring组成
1.4、拓展
在Spring的官网有介绍:现代Java开发!说白了就是基于Spring的开发
- SpringBoot
- 一个快速开发的脚手架
- 基于SpringBoot可以快速的开发单个微服务
- 约定大于配置
- Spring Cloud
- SpringCloud是基于SpringBoot实现的。
学习SpringBoot的前提是需要完全掌握Spring以及SpringMVC的知识!
2、IOC(控制反转)理论推导
-
UserDao接口
-
UserDaoImpl实现类
-
UserService业务接口
-
UserServiceImpl业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改代码!,如果程序的代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个set接口来实现。而程序设计的思想已经发生了革命性的变化!
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序员手上!
- 使用了set注入以后,程序不在具有主动性,而是变成了被动的接受对象!
这种思想,从本质上解决了问题,我们程序员不在管理对象的创建了,系统的耦合性大大降低,可以更加专注的在业务的实现上!这是IOC的原型!
2.1、IOC(控制反转)的本质
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法也有人认为DI知识IoC的另外一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,使用控制反转后将对象的创建转移给第三方,个人认为所谓的控制反转就是:获得的依赖反转了。
采用XML方式配置Bean的时候,Bean的定义信息和实现是分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注入的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)
2.2、控制反转再理解
控制:讲的是谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring框架进行创建。
反转:指的是程序本身不在创建对象,而变成被动的接收对象
控制反转:指对象的创建权由原来的程序本身去创建,变成由Spring框架创建,而程序则成为对象的被动接受者。
依赖注入:就是利用set方法进行注入
IoC就是一种编程思想,由主动的编程变成被动的接受
总结:所谓的IoC就是,对象由Spring来进行创建,管理,装配!对象的属性是由Spring容器(Beans)设置的
3、HelloSpring
<?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 类型();
而bean 标签中的 id相当于变量名,class等于要new的对象
property 相当于给对象中的属性设置一个值!
-->
<bean id="hello" class="com.haha.entity.Hello">
<property name="str" value="Hello,Spring!"/>
</bean>
</beans>
import com.haha.entity.Hello;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了,我们要去使用的话直接去里面读取就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.getStr());
}
}
思考问题?
-
Hello对象时谁创建的?
-
hello对象是由Spring创建的
-
Hello对象的属性是怎么设置的?
-
hello对象的属性是由Spring容器设置的
这个过程就叫做控制反转;
4、IoC创建对象的方式
-
Spring默认使用无参构造创建对象,默认!
<!--1.使用无参构造创建类--> <bean id="user" class="com.haha.entity.User"> <property name="name" value="王旭东"/> </bean>
在实体类有无参构造器的情况下,Spring容器会默认为我们创建对象
-
假设我们要使用有参构造创建对象。
-
下标构造创建对象
<!--2.下标构造创建对象--> <bean id="user" class="com.haha.entity.User"> <constructor-arg index="0" value="下标构造"/> </bean>
-
根据参数类型创造对象
<!--3.根据参数类型创造对象--> <bean id="user" class="com.haha.entity.User"> <constructor-arg type="java.lang.String" value="王haha"/> </bean>
注:本方法不建议使用,因为当参数过多出现相同的类型时,该方法就不能使用。所以此方法不适用
-
直接通过参数名设置参数来创建对象
<!--4.直接通过参数名来设置构造参数创建对象--> <bean id="user" class="com.haha.entity.User"> <constructor-arg name="name" value="wnaghaha"/> </bean>
-
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
5、Spring配置
5.1、别名
<!--别名-->
<alias name="user" alias="surname"/>
当我们添加了别名设置,我们就可以使用别名获取到这个对象,当然我们也可以用原本的名字。
5.2、Bean的配置
<!--
id:bean的唯一标识符,也就是我们学的对象名
class:bean对象所对应的全限定名;包名+类型
name:也可取别名,但可以同时取多个别名。别名与别名之间可以用空格,逗号和分号隔开
-->
<bean id="user2" class="com.haha.entity.User2" name="userT;alias,user22">
<property name="name" value="哈哈哈哈"/>
</bean>
5.3、import导入
这个import,一般用于团队开发使用,他可以将多个配置文件导入合并成为一个
假设,现在项目中有多个人同时开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的配置文件
例如:通过在applicationContext.xml中通过import标签将beans.xml,beans1.xml,beans2.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="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
</beans>
在使用的时候直接使用总的配置文件就可以了
6、依赖注入
6.1、构造器注入
在第四节IoC创建对象的方式中已有讨论
6.2、Set方式注入(重点)
- 依赖注入:Set注入!
- 依赖:bean对象的创建依赖于容器!
- 注入:bean对象中的所有属性,由容器来注入!
【环境搭建】
-
复杂对象
package com.haha.entity; public class Address { private String addr; public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } }
-
真实测试对象
package com.haha.entity; import java.util.*; public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> game; private String wife; private Properties info;
-
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="student" class="com.haha.entity.Student"> <!--第一种:普通的属性值注入--> <property name="name" value="王旭东"/> <property name="address" ref="address"/> </bean> <bean id="address" class="com.haha.entity.Address"> <property name="addr" value="金山东路一号"/> </bean> </beans>
-
测试类
import com.haha.entity.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student); } }
完善后续注入(八种类型的注入)
<?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.haha.entity.Student">
<!--第一种:普通的属性值注入 value -->
<property name="name" value="王旭东"/>
<!--第二种:引用类型Bean注入 ref -->
<property name="address" ref="address"/>
<!--第三种:数组注入-->
<property name="books">
<array>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
<value>红楼梦</value>
</array>
</property>
<!--第四种:list注入-->
<property name="hobbys">
<list>
<value>唱</value>
<value>跳</value>
<value>rap</value>
<value>篮球</value>
</list>
</property>
<!--第五种:Map注入-->
<property name="card">
<map>
<entry key="校园卡" value="22180895"/>
<entry key="身份证" value="342201"/>
</map>
</property>
<!--第六种:Set注入-->
<property name="game">
<set>
<value>ARK</value>
<value>LOL</value>
<value>CF</value>
</set>
</property>
<!--第七种:NULL值注入-->
<property name="wife">
<null/>
</property>
<!--第八种:properties值注入(相当于键值对)-->
<property name="info">
<props>
<prop key="username">root</prop>
<prop key="password">abc123</prop>
</props>
</property>
</bean>
<bean id="address" class="com.haha.entity.Address">
<property name="addr" value="金山东路一号"/>
</bean>
</beans>
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.haha.entity.User" p:age="18" p:name="王哈哈"/>
<!--c命名空间注入,可以通过构造器注入:construct-args-->
<bean id="user2" class="com.haha.entity.User" c:age="18" c:name="哈哈哈哈"/>
</beans>
测试:
@Test
public void test02(){
var context = new ClassPathXmlApplicationContext("userbeans.xml");
var 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"
6.4、Beans的作用域
-
单例模式(Spring的默认机制)
只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一的实例
<bean id="user2" class="com.haha.entity.User" c:age="18" c:name="哈哈哈哈" scope="singleton"/>
-
原型(多例)模式:
每次从容器中get的时候,都会产生一个新的bean实例,类似于new。
<bean id="user2" class="com.haha.entity.User" c:age="18" c:name="哈哈哈哈" scope="prototype"/>
-
其余的request、session、application这些个只能在web开发中用到!
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配方式
- 在xml中显示的配置
- 在Java中显示的配置
- 隐式的自动装配bean【重要】
7.1、测试
环境搭建:一个人有两个宠物!
7.2、ByName自动装配
<!--
ByName:会自动在容器的上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="people" class="com.haha.entity.People" autowire="byName">
<property name="name" value="大帅哥"/>
</bean>
7.3、ByType自动装配
<!--
ByName:会自动在容器的上下文中查找,和自己对象set方法后面的值对应的beanid!
ByType:会自动在容器的上下文中查找,和自己对象中的属性类型相同的bean!(但是必须保证全局中此类型只有一个)
-->
<bean id="people" class="com.haha.entity.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.
要使用注解须知:
7.4.1、导入约束
在xml的命名空间中添加以下约束
xsi:schemaLocation="http://www.springframework.org/schema/beans
7.4.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)容器中存在,且符合命名规则!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
测试代码:
public class People {
private String name;
//如果显示的定义了Autowired的required属性为false,说明这个对象可以为NULL,否咋不允许为空
@Autowired(required = false)
private Dog dog;
@Autowired
private Cat cat;
如果@Autowired自动装配的环境比较复杂的时候,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”)来配合@Autowired的使用,指定唯一的bean对象注入
public class People {
private String name;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
@Autowired
@Qualifier(value = "cat1")
private Cat cat;
}
@Resource注解
public class People {
private String name;
@Resource(name = "dog222")
private Dog dog;
@Resource(name = "cat1")
private Cat cat;
}
小结:
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求对象存在!【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过bytype实现!如果两个都找不到的情况下,就报错!【常用】
- 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byname的方式实现
8、使用注解开发
在Spring4之后,要使用注解开发,必须要保证AOP的包导入项目中了
使用注解需要导入context约束,增加注解的支持
8.1、bean
<bean id="user" class="com.haha.entity.User"/>
8.2、属性如何注入
package com.haha.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于<bean id="user" class="com.haha.entity.User"/>
//@Component组件(英文的意思就是组件)
@Component
public class User {
//属性注解相当于:<property name="name" value="王哈哈"/>
//@Value注解也可以放在set方法上,在set方法上也可以注入进去
@Value("王哈哈")
public String name;
public void setName(String name) {
this.name = 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、作用域
@Component
@Scope("prototype")
public class User {
//属性注解相当于:<property name="name" value="王哈哈"/>
//@Value注解也可以放在set方法上,在set方法上也可以注入进去
@Value("王哈哈")
public String name;
public void setName(String name) {
this.name = name;
}
}
8.6、小结
xml与注解:
- xml更加万能,使用与任何场合!维护简单方便
- 注解不是自己的类使用不了,维护相对复杂!
xml与注解的最佳实践:
-
xml用来管理bean;
-
注解只负责完成属性的注入;
-
我们在使用的过程中,只需要注意一个问题;必须让注解生效,这时我们就需要开启注解的支持
<!--指定要扫描的包,这个包下面的注解就会生效--> <context:component-scan base-package="com.haha"/> <!--开启Spring注解的驱动--> <context:annotation-config/>
9、使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做
JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心的功能
-
实体类
//这里这个注解的意思,就是说明这个类被Spring接管了,并注册到容器中 @Component public class User { //注入的值 @Value("王哈哈") private String name; public User() { } public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
-
配置类
package com.haha.config; import com.haha.entity.User; import org.springframework.context.annotation.*; //@Configuration也会被容器接管,并注册到容器中,因为这个注解的源文档就有@Component,也就是Configuration本身就是个组件 //而@Configuration注解代表了这是一个配置类,与之前的beans.xml功能相同 @Configuration @ComponentScan("com.haha.entity") @Import(MyConfig2.class) public class MyConfig { //注册一个bean,就相当于我们之前在xml中写的一个bean标签 //这个方法的名字就相当于bean标签中的id属性 //这个方法的返回值相当于bean标签中的class属性 @Bean public User getUser(){ //返回值就是返回要注入到bean的对象 return new User(); } }
-
测试类
public class MyTest { @Test public void test1(){ //如果完全的使用了配置类的方式去做,我们只能够通过AnnotationConfig上下文来获取容器,通过配置类的class对象来加载! var context = new AnnotationConfigApplicationContext(MyConfig.class); User user = (User) context.getBean("getUser"); System.out.println(user); } }
这种纯Java的配置方式,在SpringBoot中随处可见!
10、代理模式
为什么要学习代理模式?因为代理模式就是SpringAOP的底层设计模式!【SpringAOP和SpringMVC】
代理模式的分类:
-
静态代理
-
动态代理
10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人!
代码步骤:
-
接口
//租房 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() { kanfang(); host.rent(); hetong(); fare(); } public void kanfang(){ 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(); } }
代理模式的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的事务
- 公共的业务也就交给了代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
代理模式的缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍-开发效率会变低
10.2、静态代理再理解
AOP:面向切面编程!
我们在日常的开发中,遵循纵向开发的模式如下图所示。当要求修改其中一个业务的时候,我们通常不修改源代码,而是采用面向切面的编程思想(AOP)对所要求的业务实现修改操作。
-
抽象接口
public interface UserService { public void add(); public void delete(); public void update(); public void query(); }
-
真实角色
public class UserServiceImpl implements UserService{ @Override public void add() { System.out.println("添加了一个用户"); } @Override public void delete() { System.out.println("删除了一个用户"); } @Override public void update() { System.out.println("更新了一个用户"); } @Override public void query() { System.out.println("查询了一个用户"); } }
-
代理角色
public class UserServiceProxy implements UserService{ private UserServiceImpl userServiceImpl; public void setUserServiceImpl(UserServiceImpl userServiceImpl) { this.userServiceImpl = userServiceImpl; } @Override public void add() { log("add"); userServiceImpl.add(); } @Override public void delete() { log("delete"); userServiceImpl.delete(); } @Override public void update() { log("update"); userServiceImpl.update(); } @Override public void query() { log("query"); userServiceImpl.query(); } private void log(String name){ System.out.println("打印了"+name+"方法"); } }
-
客户端访问代理角色
public class Client { public static void main(String[] args) { var userService = new UserServiceImpl(); var serviceProxy = new UserServiceProxy(); serviceProxy.setUserServiceImpl(userService); serviceProxy.add(); } }
10.3、动态代理
因为在静态代理中有一个缺点就是每次代理一个角色,代码量会翻倍开发效率变低。这时候有个功能就可以被使用,就是Java的反射功能,反射的时候可以动态的加载一些类,动态代理的底层就是反射。
- 动态代理和静态代理的角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的!
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口----JDK原生的动态代理【此项目中使用】
- 基于类:cglib
- Java字节码实现:javasist
需要了解两个JDK中的类:Proxy(代理),InvocationHandler(调用处理程序)
//proxy:生成动态代理实例的
//InvocationHandler:调用处理程序并返回一个结果
动态代理的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的事务
- 公共的业务也就交给了代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
生成万能代理类:
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);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
var invoke = method.invoke(target, args);
return invoke;
}
}
测试类:
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色,不存在
ProxyInvocationHandler proxyHandler = new ProxyInvocationHandler();
proxyHandler.setTarget(userService);
//动态生成代理类
UserService proxy = (UserService) proxyHandler.getProxy();
proxy.add();
}
}
11、AOP
11.1、什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的一种延续,是软件开发中的一个热点。也是Spring框架中的一个重要的内容,是函数式编程中的一种衍生的范型、利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP在Spring中的作用
我的理解:1. AOP有两个概念(切面、通知)2. OOP有两个概念(Target、Proxy)3. 连接AOP和OOP的桥梁就是:切入点和连接点。
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的。但是我们需要关注的那部分,就是横切关注点。如日志、安全、缓存、事务等等…
- 切面(Aspect):横切关注点就是被模块化的特殊对象。即,他是一个类。
- 通知(Advice):切面必须要完成的工作。即,他是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的"地点"的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能。
11.3、使用Spring实现AOP
execution表达式:
execution(* com.haha.Service.UserServiceImpl.*(. .))
第一个*表示返回值类型为任意类型
第二个*表示任意方法名
(. .)括号表示方法里的参数,两个句点表任何类型的参数
【重点】使用AOP织入,需要导入一个依赖包!
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
方式一:使用Spring的API接口实现AOP操作
-
事件通知:
public class AfterLog implements AfterReturningAdvice { //returnValue:返回值 @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("执行了"+method.getName()+"方法返回结果为:"+returnValue); } }
-
织入操作的配置文件
<!--注册bean--> <bean id="userService" class="com.haha.Service.UserServiceImpl"/> <bean id="beforeLog" class="com.haha.log.BeforeLog"/> <bean id="afterLog" class="com.haha.log.AfterLog"/> <!--方式一:使用原生的Spring API接口--> <!--配置AOP:需要导入AOP的约束--> <aop:config> <!--切入点配置: expression(表达式) execution(要执行的位置) AspectJ语法:execution(修饰符匹配?返回值类型 操作类型的匹配?名称匹配(参数匹配)抛出异常匹配);这里第一个*是返回值类型 表达式: [方法访问修饰符] 方法返回值 包名.类名.方法名(方法的参数) 第一个*号:表示返回类型, *号表示所有的类型。 两个句点表示任何参数 --> <aop:pointcut id="pointcut" expression="execution(* com.haha.Service.UserServiceImpl.*(..))"/> <!--执行环绕增加: 我们把beforeLog切入到pointcut方法上面 --> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config>
-
测试
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //动态代理代理的是接口,而不是具体的实现类 UserService userService = context.getBean("userService", UserService.class); userService.add(); } }
方式二:自定义来实现AOP
定义一个切面,然后传要切入的哪些点,再传要切入的哪些方法。
-
配置文件
<!--方式二:自定义类--> <bean id="diy" class="com.haha.DIY.DiyPointCut"/> <aop:config> <!--自定义切面,ref是要在切面中插入的类--> <aop:aspect ref="diy"> <!--切入点--> <aop:pointcut id="point" expression="execution(* com.haha.Service.UserServiceImpl.*(..))"/> <!--通知--> <aop:after method="after" pointcut-ref="point"/> <aop:before method="before" pointcut-ref="point"/> </aop:aspect> </aop:config>
-
自定义的插入类
public class DiyPointCut { public void before(){ System.out.println("======================前置方法============================"); } public void after(){ System.out.println("======================后置方法============================"); } }
方式三:使用注解实现AOP
-
注解实现切入
//方式三:注解实现AOP操作 @Aspect public class AnnotationPointCut { @Before("execution(* com.haha.Service.UserServiceImpl.*(..))") public void before(){ System.out.println("======================前置方法============================"); } @After("execution(* com.haha.Service.UserServiceImpl.*(..))") public void after(){ System.out.println("======================后置方法============================"); } //在环绕增强中我们可以设置一个参数,代表我们要获取处理切入的点 @Around("execution(* com.haha.Service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("环绕前"); var proceed = joinPoint.proceed(); //这一句式执行原本的方法 System.out.println("环绕后"); } }
-
配置文件开启AOP注解驱动
<!--方式三:使用注解实现AOP--> <bean id="annotation" class="com.haha.DIY.AnnotationPointCut"/> <aop:aspectj-autoproxy/>
12、整合Mybatis
步骤:
- 导入相关的jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
- mybatis-spring
- 编写配置文件
- 测试
12.1、回忆Mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper.xml
- 测试
12.2、Mybatis-Spring整合过程
在整合过程中,我们在编写Spring、Mybatis配置文件的时候通常分开几个配置文件来写。最后设置一个总的Spring配置文件,将Spring的注册文件导入即可。如下图所示:
<!--专注于业务配置,常用的mybatis-spring的配置我们可以导入-->
<import resource="Mybatis-Spring.xml"/>
<!--在Spring中注册userMapper-->
<bean id="userMapper" class="com.haha.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
-
编写数据源
<!--DataSource:使用Spring的数据源替换Mybatis的位置 c3p0 bdcp druid 我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="abc123"/> </bean>
-
SqlSessionFactory
<!--使用Spring进行SqlSessionFactory的创建--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--绑定Mybatis的配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--Mybatis与Spring的配置文件中的注册Mapper的配置不能同时存在--> <property name="mapperLocations" value="classpath:com/haha/dao/*.xml"/> </bean>
-
SqlSessionTemplate
<!--SqlSessionTemplate:就是我们使用的SqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--SqlSessionTemplate中没有set设置方法,我们只能通过构造方法进行传参--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
需要给接口添加实现类
public class UserMapperImpl implements UserMapper{ private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> selectUser() { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); return userMapper.selectUser(); } }
-
将自己写的实现类,注入到Spring中
<!--在Spring中注册userMapper--> <bean id="userMapper" class="com.haha.dao.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
-
测试使用即可
public class MyTest { @Test public void test01() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); } } }
13、声明式事务
13.1、事务的回顾
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分重要,涉及到数据一致性问题,不能马虎!
- 事务确保完整性和一致性;
事务ACID原则:
-
原子性
-
一致性
-
隔离性
- 多个业务可能操作同一个资源,防止数据破坏
-
持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!
13.2、Spring中的事务管理
-
声明式事务:AOP
-
编程式事务:需要在代码中,进行事务的管理,耦合性较高。
思考:
为什么需要事务?
- 如果不能配置事务,可能存在数据提交不一致的情况
- 如果我们不在spring中配置声明式事务,我们就要在代码中手动配置事务。
- 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不能马虎大意!
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.selectUser();
}
}
5. 将自己写的实现类,注入到Spring中
```xml
<!--在Spring中注册userMapper-->
<bean id="userMapper" class="com.haha.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
-
测试使用即可
public class MyTest { @Test public void test01() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); } } }
13、声明式事务
13.1、事务的回顾
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分重要,涉及到数据一致性问题,不能马虎!
- 事务确保完整性和一致性;
事务ACID原则:
-
原子性
-
一致性
-
隔离性
- 多个业务可能操作同一个资源,防止数据破坏
-
持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!
13.2、Spring中的事务管理
-
声明式事务:AOP
-
编程式事务:需要在代码中,进行事务的管理,耦合性较高。
思考:
为什么需要事务?
- 如果不能配置事务,可能存在数据提交不一致的情况
- 如果我们不在spring中配置声明式事务,我们就要在代码中手动配置事务。
- 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不能马虎大意!