Spring

1、Spring

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

1.1、优点

  • Spring是一个开源的免费的框架(容器)!
  • Spring是一个轻量级的、非入侵式的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事务的处理,对框架整合的支持

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

1.2、组成

Spring有七大功能模块,分别是Spring Core,AOP,ORM,DAO,MVC,WEB,Content。 Core模块是Spring的核心类库,Spring的所有功能都依赖于该类库,Core主要实现IOC功能,Sprign的所有功能都是借助IOC实现的。

在这里插入图片描述

2、IOC理论推导

原来:

  1. UserDao 接口
  2. UserDaoImpl 实现类
  3. Use’r’Service 业务接口
  4. UserServiceImpl 业务实现类

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

我们使用一个Set接口实现

private UserDao userDao;

//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
     this.userDao = userDao;
}
  • 之前,程序是主动创建对象!控制权在程序员手上
  • 使用了set注入后,程序不在具有主动性,而是变成了被动的接收对象!

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

IOC本质

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

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

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

3、HelloSring

实体类pojo:

package com.vekzjj.pojo;
public class Hello {
    private String str;
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }
    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
        bean = 对象 相当于new Hello()
        id = 变量名
        class = new的对象
        property 相对于给对象中的属性设置一个值
-->
    <bean id="hello" class="com.vekzjj.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

测试:

public class DemoTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象!
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中管理了,我们要使用直接去里面取出来就行了
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

输出:

Hello{str='Spring'}
Process finished with exit code 0

思考:

  • Hello对象是谁创建的?

    hello对象是由Spring创建的

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

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

<!--    使用Spring来创建对象,在Spring这些都称为Bean
        bean = 对象 相当于new Hello()
        id = 变量名
        class = new的对象
        property 相对于给对象中的属性设置一个值
-->

这个过程就叫控制反转:

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

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

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

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

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

4、IOC创建对象的方式

  1. 使用无参构造方法创建对象,默认!

  2. 假设我们要使用有参构造创建对象

    1. 下标赋值

      <!--第一种通过下标赋值-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg index="0" value="vekzjj"/>
      </bean>
      
    2. 类型

      <!--第二种通过类型创建-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg type="java.lang.String" value="vekzjj"/>
      </bean>
      
    3. 参数名

      <!--第三种,直接通过参数名来赋值-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg name="name" value="vekzjj"/>
      </bean>
      

5、Spring配置

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

5.1、别名

<alias name="原来的名字" alias="你要起的名字"/>
<alias name="user" alias="user2"/>
User user = (User) context.getBean("user2");
user.show();

5.2、Bean的配置

<!--
id:bean的唯一标识符,也就相当于对象名
class:bean 对象所对应的全限定名:包名 + 类型
name:别名 相当于<alias>,而且name可以取多个别名
-->
<bean id="user" class="com.vekzjj.pojo.User" name="user2,user3">
    <property name="name" qvalue="vekzjj"/>
</bean>

5.3、import

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

applicationContext.xml:

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

假设,现在项目中由多个人开发,这三个人负责不同类的开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的,用applicationContext.xml导入,使用的时候,直接使用总的配置applicationContext.xml就行了

6、依赖注入

6.1、构造器注入

  1. 使用无参构造方法创建对象,默认!

  2. 假设我们要使用有参构造创建对象

    1. 下标赋值

      <!--第一种通过下标赋值-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg index="0" value="vekzjj"/>
      </bean>
      
    2. 类型

      <!--第二种通过类型创建-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg type="java.lang.String" value="vekzjj"/>
      </bean>
      
    3. 参数名

      <!--第三种,直接通过参数名来赋值-->
      <bean id="user" class="com.vekzjj.pojo.User">
          <constructor-arg name="name" value="vekzjj"/>
      </bean>
      

6.2、Set方式注入【重点】

  • 依赖注入:本质是Set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,又容器注入

【环境搭建】

  1. 复杂类型

    package com.vekzjj.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;
    }
    
  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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="address" class="com.vekzjj.pojo.Address">
            <property name="address" value="西安"/>
        </bean>
    <!--普通值注入,value-->
        <bean id="student" class="com.vekzjj.pojo.Student">
            <property name="name" value="vekzjj"/>
    <!--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="QQ" value="2088374723"/>
                    <entry key="电话" value="13999007878"/>
                </map>
            </property>
    <!--Set-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>csgo</value>
                    <value>永劫无间</value>
                </set>
            </property>
    <!--null-->
            <property name="wife">
                <null/>
            </property>
    <!--Properties-->
            <property name="info">
                <props>
                    <prop key="学号">20202501033</prop>
                    <prop key="班级">20-23</prop>
                    <prop key="sex"></prop>
                </props>
            </property>
        </bean>
    </beans>
    
  4. 测试类

    public class DemoTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            Student student = (Student) context.getBean("student");
            System.out.println(student.toString());
        }
    }
    
  5. 输出

    Student{
        name='vekzjj',
        address=Address{address='西安'},
        books=[红楼梦, 西游记, 水浒传, 三国演义],
        hobbys=[听歌, 打游戏, 看电影],
        card={
            QQ=2088374723,
            电话=13999007878
        },
        games=[LOL, csgo, 永劫无间], wife='null',
        info={
            学号=20202501033,
            班级=20-23,
            sex=男
        }
    }
    

6.3、第三方式注入

1、 p-namespace

  1. 在bean的namespace中加入:

    xmlns:p="http://www.springframework.org/schema/p"
    
  2. <!--p命名空间注入可以直接注入属性的值-->
        <bean id="user" class="com.vekzjj.pojo.User" p:name="vekzjj" p:age="20"/>
    

2、c-namespace

  1. 在bean的namespace中加入:

    xmlns:c="http://www.springframework.org/schema/c"
    
  2. <!--c命名空间注入,通过构造器注入-->
    <bean id="user2" class="com.vekzjj.pojo.User" c:name="zjj" c:age="20"/>
    

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

6.4、bean的作用域(scope)

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  1. 单例模式(Spring默认机制)

    <bean id="user2" class="com.vekzjj.pojo.User" c:name="zjj" c:age="20" scope="singleton"/>
    
  2. 原型模式:每次从容器中get的时候,都会产生一个新对象

    <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
    
  3. 其他的request、session、application(这些只能在web开发中使用到!)

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示配置
  3. 隐式的自动装配bean【重要】

7.1、测试

环境搭建:

一个人有两个宠物!

猫:
public class Cat {
    public void shout(){
        System.out.println("miao~");
    }
}
狗:
package com.vekzjj.pojo;public class Dao {
    public void shout(){
        System.out.println("wang~");
    }
}
人:
public class People {
    private Cat cat;
    private Dao dao;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dao getDao() {
        return dao;
    }

    public void setDao(Dao dao) {
        this.dao = dao;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dao=" + dao +
                ", name='" + name + '\'' +
                '}';
    }
}
  
<?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="cat" class="com.vekzjj.pojo.Cat"/>
    <bean id="dog" class="com.vekzjj.pojo.Dao"/>

    <bean id="people" class="com.vekzjj.pojo.People">
        <property name="name" value="vekzjj"/>
        <property name="cat" ref="cat"/>
        <property name="dao" ref="dog"/>
    </bean>
</beans>

7.2、ByName自动装配

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

7.3、ByType自动装配

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

byType弊端:如果有两个相同的对象,就无法处理!

总结:

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

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

要使用注解须知:

  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>
    

@Autowired:直接在pojo的属性上使用即可,也可以在set方式上使用!

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

科普:

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

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

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用

@Qualifier(value = "xxx"去配合@Autowired的使用,指定一个唯一的bean对象注入!

@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog11")
private Dog dog;
private String name;

@Resource注解

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

@Autowired和@Resource的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired默认通过byType的方式实现【常用】
  • @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到,则报错

8、使用注解开发

注意:

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

  2. 使用注解需要导入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/>
    
    </beans>
    

8.1、注解说明

  • @Autowired:自动装配通过类型、名字。

    • 如果@Autowired自动装配的环境比较复杂,我们可以使用@Qualifier(value = "xxx"去配合@Autowired的使用,指定一个唯一的bean对象注入!
  • @Nullable: 字段标记了这个注解,说明这个字段可以为null

  • @Resource:自动装配通过名字、类型。

  • @Component:放在类上,说明这个类被Spring管理了,等价于

  • @Value:放在属性字段或者set方法上,等价于

    <bean id="user" class="com.vekzjj.pojo.User">
        <property name="name" value="vekzjj"/>
    </bean>
    
  • @Scope:作用域,参数有prototype、singleton

8.2、衍生注解

@Component有几个衍生注解,和@Component功能一样,我们在web开发中,会按照MVC三层架构分层

  • dao【@Repository】
  • service【@Service】
  • controller【@Controller】

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

9、使用Java的方式配置Spring

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

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

配置类:

package com.vekzjj.config;
import com.vekzjj.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被Spring容器托管,注册到容器中,他本是就是一个@Component
//@Configuration代表这是一个配置类,和beans.xml一样
@Configuration
@ComponentScan("com.vekzjj.pojo")
public class Myconfig {

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

import org.springframework.beans.factory.annotation.Value;

public class User {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
测试类:

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

10、代理模式

为什么要学习代理模式?

因为SpringAOP底层原理就是代理模式。【SpringAOP 和 SpringMVC】面试必问!

代理模式的分类:

  • 静态代理
  • 动态代理

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

10.1、静态代理

角色分析:

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

代码步骤:

  1. 接口

    //租房
    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

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

    package com.vekzjj.demo01;
    public class Proxy implements Rent{
        private Host host;
        public Proxy() {
        }
        public Proxy(Host host) {
            this.host = host;
        }
        @Override
        public void rent() {
            seeHouse();
            host.rent();
            contact();
            fee();
        }
        //看房
        public void seeHouse(){
            System.out.println("中介带你看房");
        }
        //收中介费
        public void fee(){
            System.out.println("收中介费");
        }
        //签租赁合同
        public void contact(){
            System.out.println("签租赁合同");
        }
    }
    
  4. 客户端访问代理角色

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

代理模式的好处:

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

缺点:

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

10.2、动态代理

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

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

lnvocationHandler:调用处理程序并返回结果的

Proxy:是生成动态代理实例对象的

动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共业务也就交给了代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理可以代理多个类,只要实现了同一个接口即可!

11、AOP

11.1、什么是AOP

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

11.2、Aop在Spring中的作用

AOP在Spring中的作用:提供声明式事务;允许用户自定义切面

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

11.3、使用Spring实现Aop

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

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

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

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

<!--    方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
<!--        切入点:
            expression:表达式
            execution:要执行的位置!
-->
        <aop:pointcut id="pointcut" expression="execution(* com.vekzjj.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

Before:

package com.vekzjj.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
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()+"被执行了");
    }
}

After:

package com.vekzjj.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
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);
    }
}

测试:

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【主要是切面定义】

<?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.vekzjj.service.UserServiceImpl"/>
    <bean id="log" class="com.vekzjj.log.Log"/>
    <bean id="afterLog" class="com.vekzjj.log.AfterLog"/>
    
    <!--    方式二:自定义类-->
    <bean id="diy" class="com.vekzjj.diy.DiyPointCut"/>

    <aop:config>
<!--        自定义切面,ref:要应用的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="point" expression="execution(* com.vekzjj.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

自定义类:

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

方式三:使用注解实现

<?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.vekzjj.service.UserServiceImpl"/>
    <bean id="log" class="com.vekzjj.log.Log"/>
    <bean id="afterLog" class="com.vekzjj.log.AfterLog"/>
    
    <!--    方式三:使用注解-->
    <bean id="annotationPointCut" class="com.vekzjj.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>
</beans>
//方式三:使用通过注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.vekzjj.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("========方法执行前========");
    }

    @After("execution(* com.vekzjj.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("========方法执行后========");
    }
    //在环绕增强中,我们可以给定一个菜蔬,代表我们要获取处理切入的点
    @Around("execution(* com.vekzjj.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);

    }
}

12、整合Mybatis

步骤:

  1. 导入相关jar包
    • junit
    • mybatis
    • mysql
    • spring
    • aop织入
    • mybatis-spring
  2. 编写配置文件
  3. 测试

需要的依赖:

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.19</version>
        </dependency>
<!--        Spring操作数据库的话,需要一个spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

12.1、Mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

12.2、Mybatis-Spring

方式一:

编写数据源配置

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--DataSource:使用Spring的数据源替换Mybatis的配置
    我们这里使用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?useSSL=false&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册Mapper-->
        <property name="mapperLocations" value="classpath:com/vekzjj/mapper/*.xml"/>
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

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

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
    <typeAliases>
        <package name="com.vekzjj.pojo"/>
    </typeAliases>
    
</configuration>

接口:

public class UserMapperImpl implements UserMapper{
    //我们的所有操作,原来都是用sqlSession来执行,现在都是使用SqlSessionTemplate;
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

测试:

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

方式二:继承SqlsessionDaoSupport实现:

编写配置:

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--DataSource:使用Spring的数据源替换Mybatis的配置
    我们这里使用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?useSSL=false&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册Mapper-->
        <property name="mapperLocations" value="classpath:com/vekzjj/mapper/*.xml"/>
    </bean>
        <bean id="userMapper2" class="com.vekzjj.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
    <typeAliases>
        <package name="com.vekzjj.pojo"/>
    </typeAliases>

</configuration>

接口:

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

13、声明式事务

13.1、回顾事务

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

事务ACID原则:

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

13.2、spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要修改原有代码
<?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:tx="http://www.springframework.org/schema/tx"
       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/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--DataSource:使用Spring的数据源替换Mybatis的配置
    我们这里使用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?useSSL=false&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册Mapper-->
        <property name="mapperLocations" value="classpath:com/vekzjj/mapper/*.xml"/>
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    
    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource"/>
    </bean>
    <!--结合AOP,实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new-->
        <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="*"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.vekzjj.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource"/>
    </bean>
    <!--结合AOP,实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new-->
        <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="*"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.vekzjj.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值