Spring5完整版详解

2022-10-15,,

1、Spring

1.1简介

2002,首次退出来Spring框架的雏形:interface21框架

Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,与2004年3月24日,发布了1.0正式版

Rod Johnson,Spring framework创始人,著名作者。

spring理念:是现有的技术更加容易使用,本身是一个大杂烩

官网地址:

https://spring.io/projects/spring-framework

官方下载地址

https://repo.spring.io/ui/native/release/org/springframework/spring/

对应jar包的导入

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>

1.2优点

Spring是一个开源的免费的框架(容器)

Spring是一个轻量级的,非入侵式的框架(不会使项目因为导入改jar包而导致项目不能运行)

控制反转(IOC),面向切面编程(AOP)

支持事物的处理,对框架整合的支持

总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

1.3组成

1.4拓展

在Spring的官网有这个介绍:现代化的Java开发!说白了就是基于Spring的开发

Spring Boot

一个快速开发的脚手架(用了SpringBoot之后就可以根据一个配置就可以开发一个网站)
基于SpringBoot可以快速的开发单个微服务
约定大于配置

Spring Cloud

SpringCloud是基于SpringBoot实现的

因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用

弊端:发展了太久之后,违背了原来的理念,配置十分繁琐,人称:“配置地狱”

2.IOC理论推导

2.1以前写项目的过程

UserDao接口

package com.tang.dao;

public interface UserDao {
public void getUser();
}

UserDaoImpl实现类

package com.tang.dao;

public class UserDaoImpl implements UserDao{
public void getUser() {
System.out.println("默认UserDao加载数据");
}
}

UserMysqlDaoImpl实现类

public class UserMysqlDaoImpl implements UserDao{
public void getUser() {
System.out.println("Mysql获取数据");
}
}

UserService业务接口

package com.tang.service;

public interface UserService {
public void getUser();
}

UserServiceImpl业务实现类

package com.tang.service;

import com.tang.dao.UserDao;
import com.tang.dao.UserDaoImpl; public class UserServiceImpl implements UserService{ //private UserDao userDao = new UserDaoImpl(); private UserDao userDao; public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//利用set进行动态实现指的注入
public void getUser() {
userDao.getUser();
}
}

模拟的用户层

public class Mytest {
@Test
public void test(){
//用户实体调用的是业务层,dao层他们不需要接触
UserService userService = new UserServiceImpl();
//控制权交给用户,用户想调用谁的实现类就直接new即可
((UserServiceImpl)userService).setUserDao(new UserMysqlDaoImpl());
userService.getUser();
}
}

测试结果

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量十分大,修改一次的成本代价十分昂贵

我们使用一个set接口实现,每当用户更改之后,不用在业务层去修改源码,只需要在用户层,根据用户所需调用相应的service层然后service层去调用dao层的代码

public class UserServiceImpl implements UserService{
//以前就需要在业务层,每当用户改变之后new 的实现类也必须随之发生变化,加了个set之后就可以在用户层根据所需通过service间接使用所需要的用户层的实现类
//private UserDao userDao = new UserDaoImpl(); private UserDao userDao; public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//利用set进行动态实现指的注入
public void getUser() {
userDao.getUser();
}
}

之前,程序是主动创建对象,控制权在程序猿手上

使用set注入后,程序不再具有主动性,而是变成了被动的接收对象

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注在业务的是线上,这是IOC的原型

2.2.IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3.HelloSpring

bean.xml创建方式

实体类User

package com.tang.pojo;

public class Hello {
private String str; public Hello() {
} public Hello(String str) {
this.str = str;
} public String getStr() {
return str;
} public void setStr(String str) {
this.str = str;
} @Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}

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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--bean = 对象-->
<!--id = 变量名-->
<!--class = new的对象-->
<!--property 相当于给对象中的属性设值-->
<bean id="hello" class="com.tang.pojo.Hello">
<property name="str" value="Spring"></property>
</bean>
</beans>

测试代码

public class MyTest {
@Test
public void test(){
//获取Spring的上下文对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了
Hello hello = (Hello) context.getBean("hello");//这里就相当于new了一个对象 System.out.println(hello.toString());
}
}

运行结果图

如果运行之后报这个错IOException parsing XML document from class path resource [beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exist

可以将该项目的pom文件的打包方式设置为jar即可解决此问题,问题出现原因就是在target中没有beans.xml文件导致

【思考问题?】

Hello对象是谁创建的?

hello对象是由Spring创建的

Hello对象的属性是怎么设置的?

hello对象的属性是由Spring容器设置的

这个过程就叫控制反转:

控制:谁来控制对象的创建,传统应用程序的对象是有程序本身控制创建的,使用Spring后,对象是由Spring来创建的

反转:程序本身不创建对象,而变成不被动的接收对象

依赖注入:就是利用set方法来进行注入的

IOC是一种编程思想,由主动地编程变成被动的接收

可以通过new ClassPathXmlApplicationContext去浏览以下底层的源码

OK,到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC一句话搞定:对象有Spring来创建,管理,装配!

4.IOC创建对象的方式

4.1使用无参构造创建对象,默认

beans.xml

<!--这里就相当于new了一个对象,不管用于不用,这里都已经创建了一个对象-->
<bean id="user" class="com.tang.pojo.User">
<property name="name" value="唐昊"></property>
</bean>

测试代码

@Test
public void UserTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
}

测试结果

4.2假设我们要使用了有参构造

下标赋值

<bean id="user" class="com.tang.pojo.User">
<constructor-arg index="0" value="User的有参构造"/>
</bean>

通过类型创建,不建议使用

 <bean id="user" class="com.tang.pojo.User">
<constructor-arg type="java.lang.String" value="User有参构造"></constructor-arg>
</bean>

通过参数名来设置

<bean id="user" class="com.tang.pojo.User">
<constructor-arg name="name" value="唐昊"></constructor-arg>
</bean>

5.Spring配置

5.1别名

<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="fasdagsd"></alias>
@Test
public void UserTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("fasdagsd");
System.out.println(user.toString());
}

5.2Bean的配置

<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class: bean对象多对应的权限定名:包名 + 类型
name:也是别名 而且name也可以同时取多个别名,每个别名之间可以用逗号,空格,分号等符号都可以实现,name起别名还是很强大的
-->
<bean id="user" class="com.tang.pojo.User" name="user2,twq">
<constructor-arg name="name" value="唐昊"></constructor-arg>
</bean>

5.3Import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并一个

假设,现在项目中有多个人开发(张三,李四,王五),这三个人复制不同的类开发,不同的类需要注册在不同的Bean中,我们可以利用import将多诱人的beans.xml合并为一个总的

使用的时候,直接使用总的配置就可以了

项目结构图

application.xml

<import resource="beans.xml"></import>
<import resource="beans2.xml"></import>
<import resource="beans3.xml"></import>

6.DI依赖注入

6.1Set方式注入(重点)

依赖注入:Set注入

依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器注入

(1)环境搭建

复杂类型
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;
//get,set方法这里就不写上了,可以自己写上
}
beans.xml
<bean id="student" class="com.tang.pojo.Student">
<!--第一种,普通的注入,value-->
<property name="name" value="唐昊"></property> </bean>
测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName()); }

完善注入信息

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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.tang.pojo.Address">
<property name="address" value="北京"></property>
</bean> <bean id="student" class="com.tang.pojo.Student">
<!--第一种,普通的注入,value-->
<property name="name" value="唐昊"></property> <!--第二种,Bean注入,使用ref-->
<property name="address" ref="address"></property> <!--第三种:数组的注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>三国</value>
<value>水浒传</value>
</array>
</property> <!--第四种:list的注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property> <!--第五种:map的注入-->
<property name="card">
<map>
<entry key="身份证" value="1111111111111111111"></entry>
<entry key="银行卡" value="33333333333333333333"></entry>
</map>
</property> <!--第六种:Set的注入-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property> <!--第七种:null的注入-->
<property name="wife">
<null></null>
</property> <!--第八种:Properties-->
<property name="info">
<props>
<prop key="学号">20220140</prop>
<prop key="性别">男</prop>
<prop key="学号">20220140</prop>
</props>
</property>
</bean>
</beans>

测试结果

7.Bean的自动装配

7.1自动装配

自动装配是Spring满足Bean依赖的一种方式

spring会在上下文中自动寻找,并自动给Bean装配属性

在Spring中有三种装配的方式

在xml中显示的配置

在Java中显示配置

隐式的自动装配Bean【重要】

7.2测试

环境搭建:一个人有两个宠物

ByName自动装配

<!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid-->
<bean id="people" class="com.tang.pojo.People" autowire="byName">
<property name="name" value="twq"></property>
<!--<property name="dog" ref="dog"></property>-->
<!--<property name="cat" ref="cat"></property>-->
</bean>

ByType自动装配

<bean id="cat" class="com.tang.pojo.Cat"></bean>
<bean id="dog111" class="com.tang.pojo.Dog"></bean>
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean !
-->
<bean id="people" class="com.tang.pojo.People" autowire="byType">
<property name="name" value="twq"></property>
<!--<property name="dog" ref="dog"></property>-->
<!--<property name="cat" ref="cat"></property>-->
</bean>

小结:

byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致

byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

7.3使用注解实现自动装配

要使用注解须知:

导入约束: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></context:annotation-config> <bean id="cat" class="com.tang.pojo.Cat"></bean>
<bean id="dog111" class="com.tang.pojo.Dog"></bean>
<bean id="people" class="com.tang.pojo.People"></bean> </beans>

在实体类上使用注解即可

public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}

测试代码

@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getDog().shot();
people.getCat().shot();
}

运行结果图

@Autowired

直接在属性山使用即可,也可以在set方法上使用

使用@Autowired我们可以不用编写set方法了,前提是你这个自动装的属性在IOC(Spring)容器中存在,且符合名字byname

8.使用注解开发

在Spring4之后,要使用注解开发,必须要保证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></context:annotation-config>
</beans>

8.1.属性如何注入

//等价于<bean id="user" class="com.tang.pojo.User"></bean>
//@Component组件,放在类上,说明这个类被Spring管理了,就是bean
@Component
public class User {
// public String name ="唐昊";
//相当于 <property name="name" value="唐昊"/>
@Value("唐昊")//给name赋值
public String name; }

8.2衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层

dao【@Repository】

service【@Service】

controller【@Controller】

这四个注解功能都是一样的,都是代表某个类注册到Spring中,装配Bean

8.3小结

xml与注解:

xml更加万能,适用于任何场合!维护简单方便

注解不是自己的类使用不了,维护相对复杂

最佳实践:

xml用来管理bean

注解只负责完成属性的注入

我们在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持

<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.tang.pojo"></context:component-scan> <context:annotation-config></context:annotation-config>

9.使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给java来做

JavaConfig是Spring的一个子项目,在Spring4之后,他就成为了一个核心功能

User实体类代码

//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("唐三")//将name的值设置为唐三
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

Config类

/*
* 这个也会被Spring容器托管,注册倒容器中,因为他本爱就是一个@Component
* @Confguration代表这是一个配置类,就是我们之前看的beans.xml*/
@Configuration
@Component("com.tang.pojo")
public class TangConfig { //注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签的id属性
//这个方法的返回值,就相当于bean标签中class属性
@Bean
public User getUser(){
return new User();//就是要返回要注入到bean的对象
}

测试类

public class MyTest {
@Test
public void test(){
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文
// 来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(TangConfig.class);
User getUser = context.getBean("getUser", User.class);//取得getUser是TangConfig中经过Bean注册过的 System.out.println(getUser.getName()); }

这种纯java的配置方式,在SpringBoot中随处可见

10.代理模式

为什么要学习代理模式?
因为这就是SpringAOP的底层!【SpringAOP和SpringMVC面试必问】

代理模式的分类:

静态代理

动态代理

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();
seeHouse();
contract();
fees();
} //看房
public void seeHouse(){
System.out.println("中介带你看房");
} //签合同
public void contract(){
System.out.println("签租赁合同");
} //收中介费
public void fees(){
System.out.println("收中介费");
}
}

④.客户访问dialing角色

public class Client {
public static void main(String[] args) {
Host host = new Host();//房东要出租房子
//中介帮房东出租房子,但是dialing角色一般会有一些附属操作
Proxy proxy = new Proxy(host); //你不用面对房东,直接找中介租房
proxy.rent();
}
}

代理模式的好处

可以使真实角色的操作更加纯粹!不用去关注一些公共的业务

公共业务就交给代理角色!实现业务的分工

公共业务发生扩展的时候,方便集中管理

缺点:

一个真是角色就会产生一个代理角色;代码量会翻倍-开发效率低

10.2加深理解

目的:在每次调用增删改查的时候打印一个日志,表明当前调用的是哪个操作,在公司里在原来的代码上修改是大忌,这时就可以采用代理模式来实现

UserService接口

public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}

UserServiceImpl代码

public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加了一个用户");
} public void delete() {
System.out.println("删除了一个用户");
} public void update() {
System.out.println("修改了一个用户");
} public void query() {
System.out.println("查询了一个用户");
}
}

UserServiceProxy代理代码

public class UserServiceProxy implements UserService{

    private UserServiceImpl userServiceimpl;

    public void setUserServiceimpl(UserServiceImpl userServiceimpl) {
this.userServiceimpl = userServiceimpl;
} public void add() {
log("add");
userServiceimpl.add();
} public void delete() {
log("delete");
userServiceimpl.delete();
} public void update() {
log("update");
userServiceimpl.update();
} public void query() {
log("query");
userServiceimpl.query();
} public void log(String name){
System.out.println("[debug]调用了"+name+"方法");
}
}

测试代码

public class MyTest {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy userServiceProxy = new UserServiceProxy();
userServiceProxy.setUserServiceimpl(userService); userServiceProxy.add();
}
}

测试结果

10.3动态代理

动态代理和静态代理角色一样

动态代理的代理类是动态生成的,不是我们直接写好的

动态dialing分为两大类:基于接口的代理,基于类的动态代理

基于接口---JDK动态代理
基于类:cglib
java字节码实现:javAssist

需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序

租房接口类

//租房
public interface Rent { public void rent();
}

真实角色Host房东

//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东要出租房子");
}
}

动态生成代理ProxyInvocationHandler

//等会这里会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler { //被代理的接口
private Rent rent; public void setRent(Rent rent) {
this.rent = rent;
} //生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this);
} //处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(rent, args);
contract();
return result;
} //看房
public void seeHouse(){
System.out.println("中介带你看房");
} //签合同
public void contract(){
System.out.println("签租赁合同");
} }

用户类

public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host(); //代理角色:现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理鴃舌来处理我们要调用的接口对象
pih.setRent(host); Rent proxy = (Rent) pih.getProxy();//这里的Proxy就是动态生成的,我们并没有写 proxy.rent();
}
}

测试结果

将ProxyInvocationHandler提取为工具类,并实现增删改查的时候打印日志的操作

项目结构图

ProxyInvocationHandler代码

package com.tang.demo04;

import com.tang.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 class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl(); //代理角色,不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.settarget(userService);//设置要代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.delete(); }
}

测试结果

动态代理的好处:

可以使真实角色的操作更加纯粹!不用去关注一些公共的业务

公共业务就交给代理角色!实现业务的分工

公共业务发生扩展的时候,方便集中管理

*一个动态代理类处理的是一个接口,一般就是对应的一类业务

一个动态代理类可以代理多个类,只要是实现类同一个接口即可

11.AOP

11.1什么是AOP

在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

11.2AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

11.3使用Spring实现Aop

【重点】使用AOP织入,需要导入一个依赖包

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>

①使用Spring的API接口

UserService接口

public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}

UserServiceImpl代码

public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加了一个用户");
} public void delete() {
System.out.println("删除了一个用户");
} public void update() {
System.out.println("修改了一个用户");
} public void select() {
System.out.println("查询了一个用户");
}
}

Log代码

public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}

AfterLog代码

public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回值结果为:"+returnValue);
}
}

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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.tang.service.UserServiceImpl"></bean>
<bean id="log" class="com.tang.log.Log"></bean>
<bean id="afterLog" class="com.tang.log.AfterLog"></bean>
<!--方式一:使用原生Spring API接口 -->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式,execution(需要执行的位置)-->
<aop:pointcut id="pointcut" expression="execution(* com.tang.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>

测试代码

public class MyTest {

    public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService"); userService.delete();
}
}

测试结果

②自定义来实现AOP

diy下的DiyPointCut类的代码

public class DiyPointCut {

    public void before(){
System.out.println("=======方法执行前======");
} public void after(){
System.out.println("=======方法执行后======");
}
}

applicationContext.xml核心代码

    <!--方式二:自定义类-->
<bean id="diy" class="com.tang.diy.DiyPointCut"/>
<aop:config>
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.tang.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>

其它代码同方式一使用Spring的API接口代码相同就不在写了

测试结果

③使用注解来实现AOP

beas.xml核心代码

<!--方式三:使用注解实现AOP-->
<bean id="annotationPoinCut" class="com.tang.diy.AnnotationPointCut"/>
<!--开启注解支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy />

AnnotationPointCut代码

//方式三:使用注解方式实现AOP
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.tang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=======方法执行前======"); }
@After("execution(* com.tang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=========方法执行后==========");
} //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.tang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature:"+signature); Object proceed = jp.proceed();//执行方法
System.out.println("环绕后"); System.out.println(proceed); }
}

测试结果

12.整合Mybatis

12.1步骤

①导入相关jar包

junit

mybatis

mysql数据库

spring相关的

aop织入

mybatis-spring

②编写配置文件

③测试

12.2回忆mybatis

步骤:

编写实体类

@Data
public class User {
private int id;
private String name;
private String pwd;
}

编写核心配置文件

<?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>
<!--引入外部配置文件-->
<!-- <properties resource="db.properties"/>-->
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.tang.pojo"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- &amp;在xml文件中与符号需要这样来转义-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.tang.mapper.UserMapper"></mapper>
</mappers> </configuration>

编写接口

UserMapper接口代码

public interface UserMapper {
public List<User> selectUser();
}

编写mapper.xml

<!--核心配置文件-->
<mapper namespace="com.tang.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis.user
</select>
</mapper>

测试

public class MyTest {
@Test
public void test() throws IOException {
String resources ="mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resources);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser(); for (User user : userList) {
System.out.println(user);
}
}
}

测试结果:

12.2Mybatis-spring

项目结构图

①编写数据源配置

<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcpp druid
我们这里使用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?serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root123456"/>
</bean>

②sqlSessionFactory

<!--slqSessionFactory-->
<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/tang/mapper/*.xml"/>
</bean>

③sqlSessionTemplate

<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

④需要给接口加实现类

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();
}
}

⑤将自己写的实现类,注入到Spring中

<bean id="userMapper" class="com.tang.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>

⑥测试使用即可

public class MyTest {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<User> userList = userMapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}

测试结果

Spring5完整版详解的相关教程结束。

《Spring5完整版详解.doc》

下载本文的Word格式文档,以方便收藏与打印。