Spring5学习专题

Spring

一、简介

Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术

官网 : http://spring.io/

官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

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

优点

1、Spring是一个开源免费的框架,容器;

2、Spring是一个轻量级的框架,非入侵式的;

3、控制反转IOC,面向切面 AOP;

4、对事物的支持,对框架的支持

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

二、组成

组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
  • Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
  • Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
  • Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
  • Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
  • Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
  • Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

拓展

  • Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
  • Spring Cloud是基于Spring Boot实现的;
  • Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
  • Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
  • SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。

三、IOC基础

1、新建项目后,写一个UserDao接口

package com.kuang.dao;

public interface UserDao {
    void getUser();
}

2、写Dao的实现类

package com.kuang.dao;

public class UserDaoImpl implements UserDao{
    public void getUser() {
        System.out.println("默认获取用户的数据");
    }
}
package com.kuang.dao;
public class UserDaoMysqlImpl implements UserDao{
    public void getUser() {
        System.out.println("默认获取数据库用户的数据");
    }
}

3、然后去写UserService的接口

package com.kuang.service;
public interface UserService {
    void getUser();
}

4、写Service的实现类

package com.kuang.service;

import com.kuang.dao.UserDao;
import com.kuang.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
    //利用动态代理
    //利用set进行动态实现值的注入!
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void getUser() {
        userDao.getUser();
    }
}

5、测试类

public class MyTest {
    public static void main(String[] args) {
        //用户实际调用的是业务层
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
    }
}

这种思想,从本质上解决了问题,我们程序员不再去管理对象的创建,而是更多的去关注业务的是实现,耦合性会大大降低,这就是IOC的原型!

IOC本质

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

IoC是Spring框架的核心内容:使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC

  • Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从IoC容器中取出需要的对象

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

四、HelloSpring

编写代码

1、编写实体类

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 + '\'' +
                '}';
    }
}

2、编写我们的spring配置文件 这里我们命名为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">
        <!-- 使用Spring创建对象,在Spring这些都称为Bean
        类型 变量名 = new 类型();
        Hello hello = new Hello();
        id = 变量名  class = new 对象
        property 相当于给对象中的属性设置
        -->
        <bean id="hello" class="com.kuang.pojo.Hello">
                <property name="str" value="Spring"/>
        </bean>
</beans>

3、测试

@Test
public void test(){
   //	通过类映射解析beans.xml文件 , 生成管理相应的Bean对象
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean : 参数即为spring配置文件中bean的id .
   Hello hello = (Hello) context.getBean("hello");
   hello.show();
}

思考

  • Hello 对象是谁创建的? hello对象是由Spring创建的

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

    hello对象的属性是由Spring容器设置的,这个过程叫做控制反转:

    • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的
    • 反转:程序本身不创建对象,而变成被动接收对象
    • 依赖注入:就是利用set方法来进行注入的

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

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

五、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="heihie"/>
    </bean>

​ 3.参数名

<!--    第三种方式:直接通过参数名来设置-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="流星"/>
    </bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!

六、Spring的配置

1、alias 别名

<!--  别名,如果添加了别名,我们也可以使用别名获取到这个对象  -->
    <alias name="user" alias="good"/>

2、Bean的配置

<!--
    id:bean 的唯一标识符,也就是相当于我们学的对象名
    class:bean 对象所对应的全限定名:包名 + 类型
    name:也就是别名,而且name可以取多个别名
    -->
    <bean id="userT" class="com.kuang.pojo.UserT" name="user2,u2">
        <property name="name" value="冰冰"/>
    </bean>

3、import

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

项目中多个人开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的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">
    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
</beans>

七、DI依赖注入

1、通过构造器注入

2、通过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 String wife;
    private Properties info;
    //Getter and Setter
}

​ 3、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.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"/>
        <!-- 第三种注入: 数组注入   -->
        <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>
            </list>
        </property>
        <!-- 第四种注入: Map -->
        <property name="card">
            <map>
                <entry key="身份证" value="111111222222221234"/>
                <entry key="电话" value="12345678912"/>
            </map>
        </property>
        <!--   Set  -->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>CS</value>
                <value>Steam</value>
            </set>
        </property>
        <!--  Null  -->
        <property name="wife">
            <null/>
        </property>
        <!-- 特殊类型 -->
        <property name="info">
            <props>
                <prop key="学号">1808030214</prop>
                <prop key="性别"></prop>
                <prop key="username">星仔</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

</beans>

​ 4.测试类

import com.kuang.pojo.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 bean = (Student) context.getBean("student");
        System.out.println(bean.toString());
    /*Student{name='流星', address=Address{address='广州'},
     books=[高等数学, 离散数学, 概率, 线性代数],
     hobbys=[听歌, 敲代码, 看电影],
     card={身份证=111111222222221234, 电话=12345678912},
     games=[LOL, CS, Steam], wife='null',
     info={学号=1808030214, 性别=男, password=123456, username=星仔}}
     */
    }
}

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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--   p命名空间注入,可以直接注入属性 -property     -->
        <bean id="user" class="com.kuang.pojo.User" p:name="星星" p:age="18"/>
        <!--   c命名空间注入, 通过构造器注入 - constructs-args     -->
        <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="bb"/>
</beans>

测试!!

import com.kuang.pojo.Student;
import com.kuang.pojo.User;
import org.junit.Test;
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 bean = (Student) context.getBean("student");
        System.out.println(bean.toString());
    /*Student{name='流星', address=Address{address='广州'},
     books=[高等数学, 离散数学, 概率, 线性代数],
     hobbys=[听歌, 敲代码, 看电影],
     card={身份证=111111222222221234, 电话=12345678912},
     games=[LOL, CS, Steam], wife='null',
     info={学号=1808030214, 性别=男, password=123456, username=星仔}}
     */
    }
    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = (User) context.getBean("user2");
        System.out.println(user);
    }

}

注意点: p命名和c命名不能直接使用,需要导入xmlns的约束才能使用

       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"

八、Bean的作用域

1.单例模式(Spring默认机制)

<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="bb" scope="singleton"/>

2、原型模式

每一个Bean都作为一个单独对象

每次从容器中get的时候都会产生一个新对象

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

3、其余的request、session、application这些只能在web开发中使用!

九、Bean的自动装配

  • 自动装配Spring满足bean依赖一种方式!

  • Spring会在上下文中自动寻找,并自动给bean装配属性!

    在Spring中有三种装配方式

    ​ 1.在xml中显示的配置

    ​ 2.在java中显示的配置

    ​ 3.隐式的自动装配bean【重点】

一、测试

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

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

二、ByName自动装配

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

三、ByType自动装配

<bean  class="com.kuang.pojo.Cat"/>
<bean  class="com.kuang.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!必须保证类型全局唯一,才能够装备bean
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
    <property name="name" value="星仔"/>
</bean>

小结:

  • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致!

四、使用注解实现自动装配

使用注解的必备条件:

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>

通过在xml中添加 <context:annotation-config/>标签可以实现注解的支持

@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;
//Getter and Setter
}

@Autowired注解自动装配比较复制,在寻找属性的时候,会根据byName和byType去寻找,如果没有就会根据@Qualifier寻找;即当@Autowired无法独自装配的时候,可以通过和@Qualifier一起使用;

@Resource 注解

@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;

@Autowired 和 @Resource 的区别

@Autowired-----先 byType 后 byName

@Resource -----先 byName 后 byType

1.@Autowired 与@Resource 与可以用来装配bean,均可以写在字段上,或写在setter方法上。

2.@Autowired 默认是按照类型来装配(byType)默认情况下依赖对象必须存在,若设为null值,则要设定required = false这个条件

3.@Resource 是JDK1.6支持的注解,默认按照名称(byName)来装配,同时名称也可以通过name属性来设定,若没有设定,默认取字段名,按照名称查找,若注解写在setter方法上默认取属性名进行装配,当找不到与名称匹配的bean时才会按照(byType)类型进行装配。若name属性一旦指定,就只会按照名称进行装配。

十、使用注解开发

在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
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/context/spring-aop.xsd">

    <context:annotation-config/>

</beans>

1.bean

2.属性如何注入

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 {
    //相当于        <property name="user" value="haahaha"/>
    @Value("hahahah")
    public String name;
}

3.衍生注解

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

  • dao【@Repository】

  • service【@Service】

  • controller【@Controller】

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

  1. 自动装配
- @Autowired :自动装配 通过属性类型,名字;
    如果Autowired不能唯一自动装配属性,则需要通过@Quelifier(value="xxx")来指定装配;
- @Resource  :自动装配 通过属性名字,类型;
- @Nullable  : 字段标记了这个注解,说明这个字段可以为null; 

5.作用域

scope:singleton(单例) 和 prototype(原型)两种

6.小结:

  • xml和注解:

    • xml更加万能,适用于任何场合!维护简单方便
    • 注解:不是自己的类使用不了,维护相对复杂!
  • xml和注解的最佳实践:

    • xml用来管理bean;
    • 注解只负责完成属性的注入;
    • 我们在使用过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
        <!--  指定要扫描的包,这个包下的注解就会生效  -->
        <context:component-scan base-package="com.kuang"/>
        <context:annotation-config/>
    

十一、使用java的方式配置Spring

抛开Spring中xml的配置,完全交给java来做!

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

1、编写一个实体类

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("heihie")//属性注入值
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

2、新建一个config配置包,编写一个KuangConfig配置类

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;

//这个也会被Spring容器托管,注册到容器中,因为它本来就调用了@Component注解
//@Configuration 代表这是一个配置类,类似与 applicationContext.xml
@Configuration
@ComponentScan("com.kuang.pojo")
public class KuangConfig {
    //注册一个bean相当于在之前的beans.xml中注册一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //方法的返回值,就相当bean标签中的class属性
    @Bean
    public User user(){
        //就是返回要注入bean的对象-----相当于刚开始学的在xml形式上帮忙new一个对象
        return new User();
    }
}
@Configuration
@ComponentScan("com.kuang.pojo")
//通过Import注解可以将配置合并成整个config配置文件,相当于bean的合并
@Import(KuangConfig.class)
public class KuangConfig2 {
    @Bean
    public User user(){
        return new User();
    }
}

3、测试

public class MyTest {
    public static void main(String[] args) {
        /*如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,
        通过配置类的class对象加载!*/
		ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.getName());
    }
}

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

十二、代理模式

SpringAOP底层实现就是通过代理模式来完成的

代理模式的分类:静态代理和动态代理

代理模式的好处:

  • 可以使真实角色更加纯粹
  • 公共业务就交给了代理角色,实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实的角色就会产生一个代理角色,代码量会翻倍,开发效率会变低!

1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,之后我们会一般做一些附属操作
  • 客户:访问代理对象的人

代码步骤:

​ 1、接口--抽象角色

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

​ 2、真实角色

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

​ 3、代理角色

package com.kuang.demo01;

public class Proxy implements Rent{
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        seeHost();
        host.rent();
        regular();
        fare();
    }
    //看房
    public void seeHost(){
        System.out.println("中介带客户看房");
    }
    //签合同
    public void regular(){
        System.out.println("引导客户签合同");
    }    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

​ 4、客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //中介帮房东租房子,代理角色一般会有附属操作
        Proxy proxy = new Proxy(host);
        //通过中介直接租房
        proxy.rent();
    }
}

关于AOP

1.抽象对象

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

2.真实对象

//真实对象
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("使用了add方法");
        System.out.println("增加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void query() {
        System.out.println("查询一个用户");
    }
    //1.改动原有的代码在公司中是大忌!
}

3.代理对象

//代理对象
public class UserServiceProxy implements UserService {
    private UserService userService;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    public void add() {
        log("add");
        userService.add();
    }
    public void delete() {
        log("delete");
        userService.delete();
    }
    public void update() {
        log("update");
        userService.update();
    }
    public void query() {
        log("query");
        userService.query();
    }
    //日志方法
    public void log(String msg){
        System.out.println("使用了" + msg +"方法");
    }
}

4.客户端

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService  =new UserServiceImpl();
        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);
        proxy.query();
    }
}

2、动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类:基于接口的动态代理 和 基于类的动态代理
    • 基于接口:JDK动态代理
    • 基于类:cglib
    • java字节码的实现:javasist

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

动态代理的好处:

  • 可以使真实角色更加纯粹
  • 公共业务就交给了代理角色,实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!
  • 一个动态代理类所代理的是一个接口,一般就是对应一类的业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可!
//万能代理类
//通过这个类自动生成--->代理类
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 {
        //动态代理的本质就是使用反射机制
        Object result = method.invoke(target, args);
        log(method.getName());
        return result;
    }
}

接口

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

真实对象

package com.kuang.demo02;

//真实对象
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("使用了add方法");
        System.out.println("增加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void query() {
        System.out.println("查询一个用户");
    }
    //1.改动原有的代码在公司中是大忌!
}

测试!

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

十三、AOP

1、什么是AOP

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

2、AOP在Spring中的作用

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

以下名词需要了解下:

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

图片

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

图片

3、使用Spring实现AOP

使用AOP织入,需要导图一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

方式一:使用Spring的API接口

1.接口和实现类

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("增加了一个用户");
    }
    public void delete() {
        System.out.println("删除了一个用户");
    }
    public void update() {
        System.out.println("更改了一个用户");
    }
    public void select() {
        System.out.println("查询了一个用户");
    }
}

2.增强类,一个前置增强,一个后置增强

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

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

方式二:使用自定义类实现AOP

1.写一个我们自己的切入类

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

2.去spring中配置

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

方式三:使用注解实现

//方式三:使用注解方式实现AOP
@Aspect     //标注这个类是个切面
public class AnnotationPointCut {
    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }

    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.kuang.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("环绕后");
    }
}
<bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
<!--  开启注解支持-->
<aop:aspectj-autoproxy/>

十四、整合Mybatis

步骤:

1.导入相关的jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring

2.编写配置文件

3.测试

1.回忆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.kuang.pojo"/>
    </typeAliases>
<!--   设置 -->
<!--    <settings>-->
<!--        <setting name="" value=""/>-->
<!--    </settings>-->

</configuration>
  • 编写接口
public interface UserMapper {
    public List<User> selectUser();
}
  • 编写Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user
    </select>
</mapper>
  • 测试

2.mybatis-spring

1.编写数据源配置

<!--  DataSources 使用数据源替换mybatis的配置 -->
<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=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

2.sqlSessionFactory

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

3.sqlSessionTemplate

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

4.需要给接口加实现类

public List<User> selectUser() {
    User user = new User(7, "小魏", "123456");
    UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
    mapper.addUser(user);
    mapper.deleteUser(7);
    return mapper.selectUser();
}

public int addUser(User user) {
    return getSqlSession().getMapper(UserMapper.class).addUser(user);
}

public int deleteUser(int id) {
    return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}

5.将自己写的实现类注入到Spring中

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

6.测试使用即可!

@Test
public void test() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
    for (User user : userMapper.selectUser()) {
        System.out.println(user);
    }
}

十五、声明事务

1、回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败!
  • 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎!
  • 确保一致性和完整性

事务的ACID原则:

  • 原子性
  • 一致性
  • 隔离性:多个业务可能操作同一个资源,防止数据损坏
  • 持久性:事务一旦提交,无论发生什么问题,结果都不会被影响,被持久化的写到存储器中!

2、Spring中的事务管理

  • 声明式事务:AOP
<!--  配置声明式事务  -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>
<!-- 结合AOP实现事务的织入   -->
<!--  配置事务通知  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<!--   给哪些方法配置事务     -->
	<!--  配置事务的传播特性:propagation  -->
    <tx:attributes>
        <tx:method name="add" propagation="REQUIRED"/>
        <tx:method name="delete" propagation="REQUIRED"/>
        <tx:method name="update" propagation="REQUIRED"/>
        <tx:method name="query" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </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>
  • 编程时事务:需要在代码中,进行事务的管理

思考:为什么需要事务

  • 如果不配置事务,可能存在数据提交不一致的情况下;
  • 如果我们不在spring中去配置声明事务,我们就需要在代码中手动配置事务!
  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!
posted @   星仔呀  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示