Spring入门笔记

1、Spring

1.1简介:给软件行业带来的春天


	Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布1.0正式版
	Rob Johnson,SpringFramework创始人,著名作者,悉尼大学博士,然而他的专业不是计算机,而是音乐学。
	Spring的理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架
	SSH:Struct2 + Spring + Hibernate!
	SSM:SpringMVC + Spring + Mybatis!
	
	官网 : 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.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>


1.2、优点

Spring是一个开源的免费的框架(容器)
Spring是一个轻量化的非入侵的框架
控制反转(IOC),面向切片编程(AOP)
支持事务的处理,对框架整合的支持
总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

1.3、组成

在这里插入图片描述

组成 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。

1.4、拓展

在这里插入图片描述

Spring Boot
	一个快速开发的脚手架
	基于SpringBoot可以快速的开发单个微服务
	约定大于配置
    Spring Cloud
	Spring Cloud 是基于Spring Boot实现的
	Spring Boot专注于快速,方便集成单个微服务个体,Spring Cloud关注全局的服务治理框架
	SpringBoot在SpringClound中起到了承上启下的作用,入宫你要学习SpringCloud必须要学习SpringBoot。

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

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

2、IOC理论推导


1、老款MVC

在这里插入图片描述

1、UserDao接口
2、UserDaoImpl实现类
3、UserService业务接口
4、UserServiceImpl业务实现类

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

private UserDao userDao;

//利用set进行动态实现值得注入!
public void setUserDao(UserDao UserDao){
	this.userDao = UserDao;
}

之前,程序是主动创建对象!控制权在程序员手中!
使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!
    
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合性大大降低。这是IOC的原型!

2、IOC的本质

	控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象方式反转了。
	IOC是Spring框架的核心内容,使用多种方式完美的实现了IOC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IOC。
	控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection,DI)

3、HelloSpring


实体类:
public class hello {

    private String Str;

    public String getStr() {
        return Str;
    }

    public void setStr(String str) {
        Str = str;
    }

    @Override
    public String toString() {
        return "hello{" +
                "Str='" + Str + '\'' +
                '}';
    }
}

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">

<!--    使用Spring创建对象,在Spring这些都称为bean

        类型 变量名 = new 类型();
        hello hello = new Hello();

        bean = 对象    等同于 new Hellp();

        id = 变量名
        class = new 的对象
        property 相当于给对象属性设置一个值!
-->
    <bean id="hello" class="com.huang.pojo.hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>
思考问题?
    hello对象是谁创建的?
    hello对象是由Spring创建的
    hello 对象的属性是怎么设置的?
    hello对象的属性是由Spring容器设置的,
    这个过程就叫控制反转;
    控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创
    建的.
    反转:程序本身不创建对象,而变成被动的接收对象.
    依赖注入:就是利用set方法来进行注入的.
    I0C是一种编程思想,由主动的编程变成被动的接收.
    可以通过newClassPathXmlApplicationContext去浏览一下底层源码 .
    OK ,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xm|配置文件中进行修改,所谓的
    loC,-句话搞定:对象由Spring来创建,管理,装配!

4、IOC创建对象的方式


1:使用无参构造创建对象,默认!
2:假设我们要使用有参构造创建读取 
	2.1、下标赋值
    <bean id="user" class="com.huang.pojo.User">
        <constructor-arg index="0" value="大傻逼"/>
    </bean>
    2.2、数据类型
    <bean id="user" class="com.huang.pojo.User">
        <constructor-arg type="java.lang.String" value="大汉堡"/>
    </bean>
	2.3、name参数名
	<bean id="user" class="com.huang.pojo.User">
            <constructor-arg name="name" value="傻逼"/>
    </bean>

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

5、Spring配置


5.1、别名

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

5.2、bean配置

<!--
        id:bean的唯一标识符,也就是相当于我们学的对象名
        class: bean对象所对应的全限定名:包名加类型
        name: 也是别名,而且name 可以同时取多个别名
-->
        <bean id="UserT" class="com.huang.pojo.UserT">
        </bean>
<!--        别名,如果添加了别名,我们也可以使用别名获取这个对象-->
        <alias name="user" alias="user2"/>

5.3、import

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

假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

使用总的配置就可以

6、依赖注入


6.1、构造器注入

6.2、Set方式注入【重点】

依赖注入:set注入!
	依赖:bean对象的创建依赖容器!
	注入:bean对象中的所有属性,由容器来注入!
	
【环境搭建】
	1.复杂类型
	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 + '\'' +
                '}';
    }

	2.真实测试对象
    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;
        
     3.测试类
    public class MyTest {
    public static void main(String[] args) {
        	//加载Spring容器上下文对象
        	ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        	Studnet studnet = (Studnet) context.getBean("student");
        	System.out.println(studnet.getName());
    	}
	}
    

完善测试

    @Override
    public String toString() {
        return "Studnet{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
    /*
     Studnet{
        name='牛',
        address=Address{address='大傻逼', name='李刚狗'},
        books=[李, 大傻逼, 真菜, 你好像有个大病],
        hobbys=[李大傻逼, 我儿子, 有个大病],
        card={
            身份证=111111111111111111, 银行卡=123456789999999999
            },
        games=[LoL, 云顶, 率土],
        wife='null',
        info={
            学号=201911111111111,
            性别=男,
            user=李刚狗,
            psw=666666
            }}
     */
}

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.huang.pojo.Address">
        <property name="address" value="大傻逼"/>
        <property name="name" value="李刚狗"/>
    </bean>

    <bean id="student" class="com.huang.pojo.Studnet">

        <!--    第一种,普通值注入,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="111111111111111111"/>
                <entry key="银行卡" value="123456789999999999"/>
            </map>
        </property>

        <!--    第六种,Set    -->
        <property name="games">
            <set>
                <value>LoL</value>
                <value>云顶</value>
                <value>率土</value>
            </set>
        </property>

        <!--    null,注入    -->
        <property name="wife">
            <null/>
        </property>

        <!--    Properties,注入
                key->value
                -->
        <property name="info">
            <props>
                <prop key="学号">201911111111111</prop>
                <prop key="性别"></prop>
                <prop key="user">李刚狗</prop>
                <prop key="psw">666666</prop>
            </props>
        </property>

    </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">

<!--   xmlns:p="http://www.springframework.org/schema/p"
        p命名空间注入,可以直接注入属性的值:property
        利用无参构造注入
-->
      <bean id="user" class="com.huang.pojo.User" p:age="18" p:name="帅逼"/>


<!--
       xmlns:c="http://www.springframework.org/schema/c"
       c命名注入,通过构造器注入
-->
      <bean id="user1" class="com.huang.pojo.User" c:age="19" c:name="牛逼"/>


</beans>

测试:

 @Test
    public void Test2(){

//        拿到Spring容器的对象
        ApplicationContext context = new ClassPathXmlApplicationContext("UserBeans.xml");
//        利用Spring容器对象拿到对象
        User user = context.getBean("user1",User.class);

        System.out.println(user.toString());
    }

注意:p命名和c命名空间不能直接使用,需要导入xml约束!

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

6.4、bean的作用域

在这里插入图片描述

在这里插入图片描述

1、单例模式(Spring默认机制):singleton

      <bean id="user1" class="com.huang.pojo.User" c:age="19" c:name="牛逼" scope="singleton"/>

在这里插入图片描述

2、原型模式(每次从容器中获取都是获取一个新对象):prototype

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-usLF7EoC-1620456761863)(C:\Users\黄\AppData\Roaming\Typora\typora-user-images\image-20210311210120396.png)]

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

7、bean的自动装配


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

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

在Spring中有三种装配方式

​ 1、在xml中显示的配置

​ 2、在Java中显示的配置

​ 3、隐式的自动装配bean【重要】

7.1、测试

环境搭建:一人两个宠物

7.2、自动装配

byName

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

byType

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

小结:

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

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

jdk1.5支持的注解,Spring2.5就支持注解。

要使用注解须知:

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>

@Autowaired

直接 属性上使用即可!也可以在set方式上使用

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

科普:

@Nullable  字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired {
    boolean required() default true;
}

测试

public class People {

    //如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;

    private String name;
}

如果 @Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【 @Autowired】完成的时候,我们可以使用@Qualifier(value= “xxx”)去配置 @Autowired的使用,指定一个唯一的bean对象注入!

public class People {

    //如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog2")
    private Dog dog;
}

@Resource注解

public class People {
//    java自带Resource
    @Resource(name = "cat")
    private Cat cat;
    @Resource(name = "cat")
    private Dog dog;
}

小结:

@@Resource和@Autowired的区别:

​ 都是用来自动装配的,都可以放在属性字段上

​ @Autowired通过byType的方式实现

​ @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错

​ 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byName的方式实现

8、使用注解开发


在Spring4之后,要使用注解开发,必须要保证aop的包导入了

在这里插入图片描述

使用注解需要导入context约束,增加注解的支持

8.1、bean

1、配置扫描哪些包下的注解
<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>
2、在指定包下编写类,增加注解
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
   public String name = "秦疆";
}
@Test
public void test(){
   ApplicationContext applicationContext =
       new ClassPathXmlApplicationContext("beans.xml");
   User user = (User) applicationContext.getBean("user");
   System.out.println(user.name);
}

8.2、属性注入

使用注解注入属性

1、可以不用提供set方法,直接再直接名上添加@value("值")
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
   @Value("秦疆")
   // 相当于配置文件中 <property name="name" value="秦疆"/>
   public String name;
}
2、如果提供了set方法,在set方法上添加@value("值")
    @Component("user")
public class User {

   public String name;

   @Value("秦疆")
   public void setName(String name) {
       this.name = name;
  }
}

8.3、衍生的注解

我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其他三个注解,功能一样,目前使用哪一个功能都一样。
@Controller:controller层,控制层
@Service:service层,服务层
@Repository:dao层,Dao层
写上这些注解,就相当于将这个类交给Spring管理装配了!

8.4、自动装配置

byName

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

byType

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

小结:

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

8.5、作用域

@scope

singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁。
prototype:多例模式。关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。
@Controller("user")
@Scope("prototype")
public class User {
   @Value("秦疆")
   public String name;
}

8.6、小结

xml与注解比较

·	XML可以适用任何场景,结构清晰,维护方便
·	注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发:推荐最佳实践

xml管理Bean
注解完成属性注入
使用过程中,可以不用扫描,扫描是为了类上的注解
	<context:annotation-config/>  
作用:
	进行注解驱动注册,从而使注解生效
	用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
	如果不扫描包,就需要手动配置bean
	如果不加注解驱动,则注入的值为了null

9、使用Java的方式配置Spring


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

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

package com.haung.config;

import com.haung.pojo.User;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 15:47 2021/3/12
 * @Modified By:
 */
//@Configuration这个也会被Spring容器接管,注册到容器中,因为他本身就是一个@Component
//@Configuration代表这个配置类,就和我们之前看的beans.xml
@Configuration
//@ComponentScan()
public class config {

    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean中的ID属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回注入到bean的对象
    }
}

import com.haung.config.config;
import com.haung.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 15:48 2021/3/12
 * @Modified By:
 */
public class MyTest {
    @Test
    public void Test(){

        //如果完全使用了配置类方式去做,我们只能通过ApplicationConfig 上下文来获取容器,通过配置类的class对象加载!
           ApplicationContext context = new AnnotationConfigApplicationContext(config.class);

        User user = context.getBean("getUser",User.class);

        System.out.println(user.toString());
    }
}

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

导入其他配置

@Configuration  //代表这是一个配置类
public class MyConfig2 {
}

@Configuration
@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {

   @Bean
   public Dog dog(){
       return new Dog();
  }

}

10、代理模式

为什么要学习代理模式方式,我们在之后的SpringBoot和SpringCloud中还会大量看到,我们需要知道这些注解的作用即可!

代理模式:这是SpringAOP的底层!【SpringAOP 和SpringMVC】

在这里插入图片描述

代理模式的分类:

10.1、静态代理

代码步骤

​ 1、接口

public interface Rent {
    public void rent();
}

​ 2、真实角色

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

​ 3、代理角色

public class Proxy {

    private Host host;

    public Proxy(){

    }

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

    public void rent(){
        seeHouse();
        host.rent();
        hetong();
        fare();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带你看那房子");
    }
    //看房
    public void hetong(){
        System.out.println("签租赁合同");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

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

public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        //代理
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

角色分析:

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

好处

可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
公共也就交给代理角色!实现了业务的分工!
公共业务发生拓展的时候,方便集中管理!

缺点

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

10.1.1加深影响

1、抽象角色

//抽象角色:增删改查业务
public interface UserService {
    void add();
    void delete();
    void update();
    void query();
}

2、真实角色

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("查询了一个用户!");
    }
}

3、代理角色

public class UserServiceProxy implements UserService{
    private UserServiceImpl userService;

    public void setUserService(UserServiceImpl userService){
        this.userService = userService;
    }

    @Override
    public void add() {
        log("add");
        userService.add();
    }

    @Override
    public void delete() {
        log("delete");
        userService.delete();
    }

    @Override
    public void update() {
        log("update");
        userService.update();
    }

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

在这里插入图片描述

10.2、动态代理

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

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

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

​ 基于接口—JDK动态代理【使用这个】

​ 基于类:cglib

​ Java字节码实现:javassist

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

动态代理的好处:

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

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

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

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

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

代码

package com.huang.demo03;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import static java.lang.reflect.Proxy.newProxyInstance;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 16:55 2021/3/14
 * @Modified By:
 */
//代理程序
public class ProxyInvotionHandler 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);
    }

    //proxy:代理类  method:代理类的调用处理程序的方法对象
    //处理代理实例上的方法调用并处理结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(target, args);
        log(method.getName());
        seeHouse();
        return result;
    }

    public void log(String msg){
        System.out.println("执行了" + msg + "方法");
    }

    //看房
    public void seeHouse(){
        System.out.println("带房客看客");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}
package com.huang.demo03;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 16:54 2021/3/14
 * @Modified By:
 */
//真实角色,房东要出租房子
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房屋出租");
    }
}
package com.huang.demo03;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 17:03 2021/3/14
 * @Modified By:
 */
//租客
public class Client {

    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理实例的调用处理程序
        ProxyInvotionHandler pih = new ProxyInvotionHandler();
        pih.setTarget(host); //将真实角色放置进去!
        Rent proxy = (Rent)pih.getProxy(); //动态生成对应的代理类!
        proxy.rent();
    }

}
package com.huang.demo03;

/**
 * @Author 黄远林
 * @Description:
 * @Date: Created in 16:53 2021/3/14
 * @Modified By:
 */
//抽象角色
public interface Rent {
    public void rent();
}

11、AOP

11.1、什么是AOP

AOP为Aspect Oriented Programming的缩写,是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合性降低,提高程序的可重用性,同时提高了开发的效率。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-00TBX7Eo-1620456761865)(C:\Users\黄\AppData\Roaming\Typora\typora-user-images\image-20210315111823142.png)]

11.2、AOP在Spring中的作用

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

​ 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…

​ 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类

​ 通知(Advice):切面必须要完成的工作。即他是类中的一个方法。

​ 目标(Target):被通知对象。

​ 代理(Proxy):向目标对象应用通知之后创建的对象。

​ 切入点(PointCut):切面通知执行的"地点"的定义。

​ 连接点(JointPoint):与切入点匹配的执行点。

11.3、使用Spring实现Aop

在这里插入图片描述

SpringAOP中,通过Advice定义横切逻辑,Spring中支持五种类型的在这里插入图片描述

即AOP在不改变原有代码的情况下,去增加新的功能

11.3.1、使用Spring实现AOP

需要导入依赖包:

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

方式一:使用Spring的API接口【主要SpringAPI接口实现】

业务接口和实现类

public interface UserService {

   public void add();

   public void delete();

   public void update();

   public void search();

}
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 search() {
       System.out.println("查询用户");
  }
}

增强类

public class Log implements MethodBeforeAdvice {

   //method : 要执行的目标对象的方法
   //objects : 被调用的方法的参数
   //Object : 目标对象
   @Override
   public void before(Method method, Object[] objects, Object o) throws Throwable {
       System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
  }
}
public class AfterLog implements AfterReturningAdvice {
   //returnValue 返回值
   //method被调用的方法
   //args 被调用的方法的对象的参数
   //target 被调用的目标对象
   @Override
   public void afterReturning(Object returnValue, Method method, Object[] args,Object target) throws Throwable {
       System.out.println("执行了" + target.getClass().getName()
       +"的"+method.getName()+"方法,"
       +"返回值:"+returnValue);
  }
}

导入依赖

<?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.kuang.service.UserServiceImpl"/>
   <bean id="log" class="com.kuang.log.Log"/>
   <bean id="afterLog" class="com.kuang.log.AfterLog"/>

   <!--aop的配置-->
   <aop:config>
       <!--切入点 expression:表达式匹配要执行的方法-->
       <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
       <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
       <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
       <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
   </aop:config>

</beans>

测试

public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.search();
  }
}
Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .

方式二:自定义来实现AOP【主要是切面定义】

目标业务类不变依旧是userServiceImpl

写一个切入类

public class DiyPointcut {

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

配置依赖

<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.kuang.config.DiyPointcut"/>

<!--aop的配置-->
<aop:config>
   <!--第二种方式:使用AOP的标签实现-->
   <aop:aspect ref="diy">
       <aop:pointcut id="diyPonitcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
       <aop:before pointcut-ref="diyPonitcut" method="before"/>
       <aop:after pointcut-ref="diyPonitcut" method="after"/>
   </aop:aspect>
</aop:config>

测试

public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.add();
  }
}

方式三:使用注解实现!

编写一个注解增强实现类

package com.kuang.config;

import org.aspectj.lang.ProceedingJoinPoint;
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.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("环绕前");
       System.out.println("签名:"+jp.getSignature());
       //执行目标方法proceed
       Object proceed = jp.proceed();
       System.out.println("环绕后");
       System.out.println(proceed);
  }
}

配置xml文件

<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

12、声明式事务


12.1、回顾事务

事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。

事务就是吧一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。

事务ACID原则:

​ 原子性

​ 一致性

​ 隔离性:多个业务,可能操作同一个资源,防止数据损坏

​ 持久性:事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中!

12.2、spring中的事务管理

声明式事务:AOP

编程式事务:需要再代码中,进行事务的管理

思考:

​ 为什么需要事务?

​ 如果不配置事务,可能存在数据提交不一致;

​ 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务!

ort org.aspectj.lang.ProceedingJoinPoint;
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.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(“环绕前”);
System.out.println(“签名:”+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println(“环绕后”);
System.out.println(proceed);
}
}


配置xml文件

```xml
<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

12、声明式事务


12.1、回顾事务

事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。

事务就是吧一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。

事务ACID原则:

​ 原子性

​ 一致性

​ 隔离性:多个业务,可能操作同一个资源,防止数据损坏

​ 持久性:事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中!

12.2、spring中的事务管理

声明式事务:AOP

编程式事务:需要再代码中,进行事务的管理

思考:

​ 为什么需要事务?

​ 如果不配置事务,可能存在数据提交不一致;

​ 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务!

​ 事务在项目的开发中十分重要,设计到数据的一致性和完整性问题,不容马虎!

本文章是通过:学习哔哩哔哩up主:遇见狂神说
学习总结
参看地址:https://space.bilibili.com/95256449?from=search&seid=11219821850283363860

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值