彼方尚有荣光在|

_xiaolin

园龄:2年9个月粉丝:3关注:5

Spring5

Spring5框架

一、Spring框架概述

1、Spring概述

1、Spring是轻量级的开源的JavaEE应用程序框架。
2、Spring可以解决企业应用开发的复杂性。
3、Spring有两个核心部分:IOC和Aop
(1)IOC:控制反转,把创建对象过程交给Spring进行管理。
(2)Aop:面向切面,不修改源代码进行功能增强。
4、Spring特点:
(1)方便解耦,简化开发。
(2)Aop编程支持
(3)方便程序的测试
(4)可以方便和其他框架进行整合
(5)方便进行事务操作
(6)降低API开发难度
5、现在课程中,选取Spring版本5.x
6、什么是bean?
在Spring中,构成应用程序主干并且由Spring IOC容器所管理的对象称为bean,bean一个由Spring IOC容器实例化、组装和管理的对象。 

2、入门案例

1、下载Spring5

spring.io官网
点击小猫(官方文件保存在Github)
然后找文件进行下载 

2、打开idea工具,创建普通java工程

3、导入Spring5相关jar包

至少需要Core Container 里四个包

4、创建一个普通类,在类中创建一个普通方法

package com.lxg.spring5;

public class User {
    public void add(){
        System.out.println("add...");
    }
} 

5、创建Spring配置文件,在配置文件中配置创建的对象

(1)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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--配置User对象创建-->
    <bean id="user" class="com.lxg.spring5.User"></bean>

</beans> 

6、进行测试代码编写

package com.lxg.spring5.testDemo;

import com.lxg.spring5.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

public class TestSpring5 {
    @Test
    public void testAdd(){
        //1.加载Spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        //2.获取配置创建的对象
        User user = context.getBean("user", User.class);
        System.out.println(user);
        user.add();

    }
} 

二、IOC容器

1、IOC底层原理

IOC(概念和原理)

1、什么是IOC?
(1)控制反转,把对象的创建和对象之间的调用过程,交给Spring进行管理。
(2)使用IOC的目的:为了耦合度降低
(3)做入门案例就是IOC实现
2、IOC底层原理
(1)xml解析,工厂模式、反射
3、画图讲解IOC底层原理
如下: 

进一步降低耦合度

2、IOC接口(BeanFactory)

1、IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
2、Spring提供了IOC容器实现的两种方式:(两个接口)
(1)BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用
 加载配置文件时不会创建对象,在获取对象(使用)时采取创建对象。
(2)ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用。
	加载配置文件的时候就会把配置文件对象进行创建
3、ApplicationContext接口有实现类
如下: 

3、IOC操作 Bean 管理

1、什么是Bean管理
(0)Bean管理指的就是两个操作
(1)Spring创建对象
(2)Spring注入属性
2、Bean管理的两种方式
(1)基于xml配置文件方式实现
(2)基于注解方式实现 

3.1、IOC操作 Bean管理(基于xml方式)

1、基于xml方式创建对象
(1)在Spring配置文件中,使用Bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性,介绍常用的属性:
	①id属性:唯一标识
	②class属性:类全路径(包类路径)
	③name属性:功能跟id一样,name可以加特殊符号
(3)创建对象时候,默认也是执行无参数构造方法完成对象创建
2、基于xml方式注入属性
(1)DI:是IOC的一个具体实现,依赖注入,就是注入属性
(2)第一种注入方式:使用set方法进行注入
	①创建类,定义属性和对应的set方法
	public class Book {
    //创建属性
    private String bname;
    private String bauthor;
    //创建属性对应的set方法
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }
}
	②在Spring配置文件配置对象创建,配置属性注入
    <!--2、set方法注入属性-->
	<bean id="user" class="com.lxg.spring5.Book">
        <!--使用property完成属性注入
            name:类里面属性名称
            value:向属性注入的值
        -->
        <property name="bname" value="西游记"></property>
        <property name="bauthor" value="吴承恩"></property>
    </bean>

(3)第二种注入方式:使用有参构造进行注入
	①创建类,定义属性,创建属性对应的有参构造方法
	public class Order {
    private String name;
    private String address;

    public Order(String name, String address) {
        this.name = name;
        this.address = address;
    }
}
	②在Spring配置文件中进行配置
	 <!--有参构造注入属性-->
    <bean id="orders" class="com.lxg.spring5.Orders">
        <constructor-arg name="name" value="电脑"></constructor-arg>
        <constructor-arg name="address" value="中国"></constructor-arg>
    </bean>
	注意:也可这么写
	<constructor-arg index="0" value="电脑"></constructor-arg>
(4)p名称空间注入(set方法注入的简化)
	①使用p名称空间注入,可以简化基于xml配置方式
	第一步添加p名称空间在配置文件中。
	<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	第二步进行属性注入,在bean标签里面进行操作
    <bean id="book" class="com.lxg.spring5.Book" p:bname="红楼梦" p:bauthor="曹雪芹">
    </bean> 
3.1.1、 IOC操作 Bean管理(xml注入其他类型属性)
1、字面量 name
(1)null值
	 <!--null值-->
        <property name="address">
            <null/>
        </property>
(2)属性值包含特殊符号
	<!--属性值包含特殊符号
               1.把<>进行转义 &lt; &gt;
               2.把带特殊符号内容写到CDATA中
			   3.格式:<![CDATA[你想写的内容]]>
        -->
        <property name="address">
            <value><![CDATA[<<南京>>]]></value>
        </property>
2、注入属性-外部bean
	(1)创建两个类service类和Dao类
		public class UserService {

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    //创建UserDao类型属性,生成set方法
    private UserDao userDao;

    public void add() {
        System.out.println("service add...");
        //原始的方法
//        UserDao userDao = new UserDaoImpl();
//        userDao.update();
        //使用set方法注入
        userDao.update();
    }
}
	(2)在service中调用dao里面的方法
	(3)在Spring配置文件中进行配置
		<!--1、service和dao对象创建-->
    <bean id="userService" class="com.lxg.spring5.service.UserService">
        <!--注入userDao对象
            name:类中的属性名称
            ref:引用的bean的id(创建userDao对象bean标签的id值)
        -->
        <property name="userDao" ref="userDaoImpl"/>
    </bean>
    <bean id="userDaoImpl" class="com.lxg.spring5.dao.UserDaoImpl"></bean>
	(4)测试
		 @Test
    public void testAdd() {
        //加载Spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        //获取bean
         UserService userService = context.getBean("userService", UserService.class);
        //调用方法
        userService.add();
    }
	
3、注入属性-内部bean
(1)一对多关系:部门和员工
	一个部门可以有多个员工,一个员工属于一个部门
	部门是一,员工是多。
(2)在实体类之间表示一对多关系
//部门类
public class Dept {
    private String deptName;

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
	public String getDname() {
        return dname;
    }
}
//员工类
public class Emp {
    private String ename;
    private String job;
    //员工属于某一个部门,使用对象形式表示
    private Dept dept;

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setJob(String job) {
        this.job = job;
    }
}
(3)在Spring配置文件中进行配置
<!--内部bean-->
    <bean id="emp" class="com.lxg.spring5.bean.Emp">
        <!--先设置两个普通的属性-->
        <property name="ename" value="lxg"></property>
        <property name="job" value="java"></property>
        <!--设置对象类型属性-->
        <property name="dept">
            <bean id = "dept" class = "com.lxg.spring5.bean.Dept">
                <property name ="dname" value = "程序员"></property>
            </bean>
        </property>
    </bean>
4、注入属性-级联赋值
(1)第一种写法
<!--级联赋值-->
    <bean id="emp" class="com.lxg.spring5.bean.Emp">
        <!--先设置两个普通的属性-->
        <property name="ename" value="xiaolin"></property>
        <property name="job" value="总经理"></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.lxg.spring5.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>
(2)第二种写法
    对象必须有get方法
<!--级联赋值-->
    <bean id="emp" class="com.lxg.spring5.bean.Emp">
        <!--先设置两个普通的属性-->
        <property name="ename" value="xiaolin"></property>
        <property name="job" value="总经理"></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="技术部"></property>
    </bean>
    <bean id="dept" class="com.lxg.spring5.bean.Dept">
    </bean> 
3.1.2 、IOC操作 Bean管理(xml注入集合属性)
1、注入数组类型属性
2、注入List集合类型属性
3、注入Map集合类型属性
4、注入Set集合类型属性
(1)创建类,定义属性和相关属性set方法
public class Stu {
    //1、数组类型属性
    private String[] courses;
    //2、List类型属性
    private List<String> list;
    //3、Map类型属性
    private Map<String,String> maps;
    //4、Set类型属性
    private Set<String> sets;

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
} 
(2)在Spring配置文件进行配置
<!--1、集合类型属性注入-->
    <bean id="stu" class="com.lxg.spring5.collectiontype.Stu">
        <!--1、数组类型属性注入-->
        <property name="courses">
            <array>
                <value>java</value>
                <value>c++</value>
                <value>pyhton</value>
            </array>
        </property>
        <!--2、数组类型属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
            </list>
        </property>
        <!--3、Map类型属性注入-->
        <property name="maps">
            <map>
                <entry key="张三" value="1"/>
                <entry key="李四" value="2"/>
                <entry key="王五" value="3"/>
            </map>
        </property>
        <!--4、Set类型属性注入-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Web</value>
                <value>Spring</value>
            </set>
        </property>
    </bean> 
5、在集合里面设置对象类型值
<!--注入list集合类型,值是对象-->
        <property name="coursesList">
            <list>
            <ref bean="course1"></ref>
            <ref bean="course2"></ref>
            </list>
        </property>
<!--创建多个course对象-->
    <bean id="course1" class="com.lxg.spring5.collectiontype.Course">
        <property name="cname" value="Spring5框架"></property>
    </bean>
    <bean id="course2" class="com.lxg.spring5.collectiontype.Course">
        <property name="cname" value="MyBatis框架"></property>
    </bean>
6、把集合注入部分提取出来共用
(1)在Spring配置文件中引入一个名称空间util
<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
(2)用util标签完成list集合注入提取
    <!--提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>西游记</value>
        <value>红楼梦</value>
        <value>三国演义</value>
    </util:list>
    <!--怎么使用-->
    <bean id="book" class="com.lxg.spring5.collectiontype.Book">
        <property name="list" ref="bookList"></property>
    </bean> 
3.1.3 、IOC 操作 Bean管理(FactoryBean)
1、Spring有两种bean,一种普通bean,另外一种工厂bean(FactoryBean)
2、普通bean:在配置文件中定义bean类型就是返回的类型
3、工厂bean:在配置文件中定义bean类型可以和返回类型不一样
	第一步:创建类,让这个类作为工厂bean,实现接口FactoryBean
	第二步:实现接口里面的方法,在实现的方法中定义返回的bean类型
	public class MyBean implements FactoryBean<Course> {

    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("java");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return FactoryBean.super.isSingleton();
    }
}
//测试
    @Test
    public void testMyBean() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }
//配置文件
<bean id="myBean" class="com.lxg.spring5.factorybean.MyBean">
    </bean> 
3.1.4、 IOC 操作 Bean管理(bean的作用域)
1、在Spring里面,设置创建bean实例是单实例还是多实例。

2、在Spring里面,默认情况下,bean是一个单实例对象
 @Test
    public void testCollection2() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = context.getBean("book", Book.class);
        //book.show();
        Book book2= context.getBean("book", Book.class);
        System.out.println(book1);
        System.out.println(book2);
    }
    
    //结果
    com.lxg.spring5.collectiontype.Book@7bd7d6d6
com.lxg.spring5.collectiontype.Book@7bd7d6d6
        
3、如何设置单实例还是多实例
(1)在Spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例    
(2)scope属性值
第一个值:默认值,singleton,表示单实例对象
第二个prototype,表示是多实例对象
        <bean id="book" class="com.lxg.spring5.collectiontype.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
    </bean>
            
 //结果
com.lxg.spring5.collectiontype.Book@5b799640
com.lxg.spring5.collectiontype.Book@6cb107fd
(3)singleton和prototype区别
第一singleton单实例,prototype多实例
第二设置scope值是singleton时候,加载Spring配置文件时就会创建单实例对象
设置scope值是prototype时候,不是在加载Spring配置文件时候创建,在调用getBean方法时候创建多实例对象
(4)request和session(了解) 
3.1.5 、IOC操作Bean 管理(bean生命周期)
1、生命周期
(1)从对象创建到对象销毁的过程
2、bean生命周期
(1)通过构造器创建bean实例(无参数构造)
(2)为bean的属性设置值和其他bean的引用(调用set方法)
(3)调用bean的初始化的方法(需要进行配置初始化的方法)
(4)bean可以使用了(对象获取到了)
(5)当容器关闭时候,调用bean的销毁方法(需要进行配置销毁的方法)
3、演示bean的生命周期
public class Orders {

    public Orders() {
        System.out.println("第一步执行无参数构造方法创建bean实例");
    }

    private String oname;

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步执行set方法设置属性值");
    }

    //创建执行的初始化方法
    public void initMethod() {
        System.out.println("第三步执行初始化方法");
    }
    //创建执行的销毁方法
    public void destroyMethod() {
        System.out.println("第五步执行销毁方法");
    }
}

测试:
     @Test
    public void testMyBean3() {
        /*ApplicationContext context =
                new ClassPathXmlApplicationContext("bean4.xml");*/
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步:获取创建的bean实例对象");
        System.out.println(orders);
        //执行销毁方法
//        ((ClassPathXmlApplicationContext) context).close();
        context.close();
    }

配置文件:
     <bean id="orders" class="com.lxg.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>
         
结果:
第一步执行无参数构造方法创建bean实例
第二步执行set方法设置属性值
第三步执行初始化方法
第四步:获取创建的bean实例对象
com.lxg.spring5.bean.Orders@5386659f
第五步执行销毁方法
         
4、bean的后置处理器,bean的生命周期有七步
(1)通过构造器创建bean实例(无参数构造)
(2)为bean的属性设置值和其他bean的引用(调用st方法)
(3)把bean实例传递bean后置处理器的方法postProcessBeforeInitialization(Object bean, String beanName)
(4)调用bean的初始化的方法(需要进行配置初始化的方法)
(5)把bean实例传递bean后置处理器的方法postProcessAfterInitialization(Object bean, String beanName) 
(6)bean可以使用了(对象获取到了)
(7)当容器关闭时候,调用bean的销毁方法(需要进行配置销毁的方法)
5、演示添加后置处理器效果
(1)创建类,实现接口BeanPostProcessor,创建后置处理器
 
public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后执行的方法");
        return bean;
    }
}
配置文件
    <!--配置后置处理器-->
    <bean id="myBeanPost" class="com.lxg.spring5.bean.MyBeanPost"></bean>
结果:
第一步执行无参数构造方法创建bean实例 
第二步执行set方法设置属性值
在初始化之前执行的方法
第三步执行初始化方法
在初始化之后执行的方法
第四步:获取创建的bean实例对象
com.lxg.spring5.bean.Orders@48bb62
第五步执行销毁方法 
3.1.6 、IOC操作Bean管理(xml自动装配)
1、什么是自动装配?
(1)根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
2、演示自动装配过程
<!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性常用两个值:
        byName根据属性名称注入,注入值bean的id值和类属性名称一致
        byType根据属性类型注入,不能有多个同类型的bean
    -->
①根据属性名称注入
    <bean id="emp" class="com.lxg.spring5.autowire.Emp" autowire="byName">
        <!--<property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="com.lxg.spring5.autowire.Dept">
    </bean>
②根据属性类型注入
 <bean id="emp" class="com.lxg.spring5.autowire.Emp" autowire="byType">
        <!--<property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="com.lxg.spring5.autowire.Dept">
    <bean</bean> 
3.1.7、IOC操作Bean管理(外部属性文件)
1、直接配置数据库信息
(1)配置德鲁伊连接池
 <!--直接配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/bjpowernode"></property>
        <property name="username" value="root"></property>
        <property name="password" value="623718"></property>
    </bean>
(2)引入德鲁伊连接池依赖jar包
2、引入外部属性文件配置数据库连接池
(1)创建外部属性文件,properties格式文件,写上数据库信息
properties配置文件:
    prop.driverClass=com.mysql.jdbc.Driver
    prop.url=jdbc:mysql://localhost:3306/bjpowernode
    prop.user=root
    prop.password=623718
(2)把外部properties属性文件引入Spring配置文件中
引入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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
(3)在Spring配置文件中使用标签引入外部属性文件
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置连接池-->
     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
         <property name="driverClassName" value="${prop.driverClass}"></property>
         <property name="url" value="${prop.url}"></property>
         <property name="username" value="${prop.user}"></property>
         <property name="password" value="${prop.password}"></property>
     </bean> 

三、IOC操作Bean管理(基于注解方式)

1、什么是注解?

  1. 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)
  2. 使用注解,注解可以作用在类上面,方法上面,属性上面
  3. 使用注解的目的:简化xml配置

2、Spring针对Bean管理中创建对象提供的注解

  1. @Component
  2. @Service
  3. @Controller
  4. @Repository

**注意:**上面四个注解功能是一样的,都可以用来创建bean实例

3、基于注解方式实现对象创建

  1. 引入依赖 spring-aop-5.3.20.jar
  2. 开启组件扫描
<!--开启组件扫描
    1、如果扫描多个包,包之间使用逗号隔开
    2、也可以直接扫描上层目录包
-->
<context:component-scan base-package="com.lxg.spring5"></context:component-scan> 
  1. 创建类,在类上面添加创建对象注解

    //在注解里面value属性值可以省略不写
    //默认值是类名首字母小写
    //UserService---userService
    @Component(value="userService")//<bean id="userService" class=""...."">;
    public class UserService {
        public void addUser() {
            System.out.println(&quot;addUser...&quot;);
        }
    } 
    
  2. 测试

@Test
public void testService(){
    ApplicationContext context =
            new ClassPathXmlApplicationContext("bean1.xml");
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService);
    userService.addUser();
}

//com.lxg.spring5.service.UserService@48b67364
//addUser... 

4、开启组件扫描细节配置

<!--示例1
    use-default-lazy-init="false"表示现在不适用默认filter,使用自己配置filter
    context:include-filter="filter1"表示使用filter1过滤器,可以设置扫描哪些内容
-->
<context:component-scan base-package="com.lxg.spring5" use-default-filters="false">
    <context:include-filter type="annotation"           expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--示例2
    下面配置扫描包所有内容
    exclude-filter="filter1"表示排除filter1过滤器,可以设置不扫描哪些内容
-->
<context:component-scan base-package="com.lxg.spring5">
    <context:exclude-filter type="annotation"
                            expression="org.springframework.stereotype.Controller"/>
</context:component-scan> 

5、基于注解方式实现属性注入

  1. @AutoWired

    • 根据属性类型进行自动装配
    • 第一步把service和dao对象创建,在service和dao类添加创建对象注解
    • 第二步在service中注入dao对象,在service类中添加dao类型属性,在属性上面使用注解
    @Service
    public class UserService {
        //定义dao类型属性
        //不需要添加set方法
        //添加注入属性注解
        @Autowired
        private UserDao userDao;
    
        public void addUser() {
            System.out.println("addUser...");
            userDao.add();
        }
    } 
    
  2. @Qualifier

    • 根据名称进行注入
    • 这个注解的使用,需要和上面@Autowired一起使用
    //定义dao类型属性
    //不需要添加set方法
    //添加注入属性注解
    @Autowired //根据类型进行注入
    @Qualifier(value = "userDaoImpl1")//根据名称进行注入
    private UserDao userDao; 
    
  3. @Resource

    • 可以根据类型注入,也可以根据名称注入
    //@Resource//根据类型进行注入
    @Resource(name = "userDaoImpl1")//根据名称进行注入 
    
    • 是 javax.annotation.Resource包下的依赖,不是Spring的,一般不建议使用。
  4. @value

    • 注入普通类型属性
    @Value(value = "lxg")
    private String name; 
    

6、完全注解开发

  1. 创建配置类,替代xml配置文件
@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = "com.lxg.spring5") //扫描包,指定扫描的包
public class SpringConfig {

} 
  1. 编写测试类
@Test
public void testService2(){
    //加载配置类
    ApplicationContext context =
            new AnnotationConfigApplicationContext(SpringConfig.class);
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService);
    userService.addUser();
} 

四、AOP

1、什么是AOP?

1、面向切面编程(方面),利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高查询的可重用性,同时提高了开发的效率。
2、通俗描述:不通过修改源代码的方式,在主干功能中添加新功能。
3、使用登录例子说明AOP 

2、AOP(底层原理)

2.1、AOP底层使用动态代理

  1. 有两种情况的动态代理

    • 第一种有接口情况,使用JDK动态代理

      创建接口实现类代理对象,增强类的方法

    • 第二种没有接口情况,使用CGLIB动态代理

      创建子类的代理对象,增强类的方法

2.2、AOP(JDK动态代理)

  1. 使用JDK动态代理,使用Proxy类里面的方法创建代理对象

1)调用newProxyInstance方法

方法有三个参数:

第一个参数,类加载器
第二个参数,增强方法所在的类,这个类实现的接口,支持多个接口
第三个参数,实现这个接口InvocationHandler,创建代理对象,写增强的部分。 
  1. JDK动态代理代码
1、创建接口,定义方法
public interface UserDao {
    public int add(int a, int b);
    public String update(String id);
}
2、创建接口实现类,实现方法
public class UserDaoImpl implements UserDao {

    @Override
    public int add(int a, int b) {
        System.out.println("add方法执行了...");
        return a+b;
    }

    @Override
    public String update(String id) {
        System.out.println("update方法执行了...");
        return id;
    }
}
3、使用Proxy类创建接口代理对象
public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
        /*Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });*/
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao =(UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}

//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    //1、把创建的是谁的对象,把谁的对象传进来
    //有参构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法之前执行..."+method.getName()+":传递的参数..."+ Arrays.toString(args));

        //被增强方法执行
        Object res = method.invoke(obj, args);
        //方法之后
        System.out.println("方法之后执行..."+obj);
        return res;
    }
} 

2.3、AOP(术语)

1、连接点
类里面哪些方法可以被增强,这些方法就称为连接点
2、切入点
实际被真正增强的方法,称为切入点
3、通知(增强)
(1)实际增强的逻辑部分称为通知(增强)
(2)通知有多种类型
 *前置通知
	*后置通知
	*环绕通知
	*异常通知
	*最终通知
4、切面
是动作
(1)把通知应用到切入点的过程 

2.4、AOP操作(准备)

1、Spring框架一般都是基于AspectJ实现AOP
(1)什么是AspectJ?
 *AspectJ不是Spring组成部分,一般把AspectJ和Spring框架一起使用,进行AOP操作。
2、基于AspectJ实现AOP操作
(1)基于xml文件方式实现
(2)基于注解方式实现(使用)
3、在项目工程里面引入AOP相关依赖 
4、切入点表达式
(1)切入点表达式的作用:知道对哪个类里面的哪个方法进行增强。
(2)语法结构:
execution([权限修饰符][返回值类型][类的全路径][方法名]([参数列表]))
权限修饰符可以省略
举例1:对com.lxg.dao.BookDao类里面的add进行增强
execution(* com.lxg.BookDao.add(..))
举例2:对com.lxg.dao.BookDao类里面的所有方法进行增强
execution(* com.lxg.BookDao.*(..))
举例3:对com.lxg.dao包里面的所有类所有方法进行增强
execution(* com.lxg.*.*(..))
第一个*表示返回值可以是任意类型,第二个*表示任意类,第三个*表示任意方法,括号里的..表示参数任意。

execution:用于匹配方法执行的连接点;
execution(* com.test.method.des..*.*(..))
1, execution()  表达式的主体
2, 第一个“*”符号    表示返回值的类型任意
3, com.test.method.des   AOP所切的服务的包名,即,需要进行横切的业务类
4, 包名后面的“..”表示当前包及子包
5, 第二个“*”    表示类名,*即所有类
6, .*(..)      表示任何方法名,括号表示参数,两个点表示任何参数类型 

2.5、AOP操作(AspectJ注解)

1、创建类,在类里面定义方法
public class User {
    public void add() {
        System.out.println("add...");
    }
}
2、创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同方法代表不同通知类型
    //增强的类
public class UserProxy {
    //前置通知
    public void before() {
        System.out.println("before...");
    }
} 
3、进行通知的配置
(1)在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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.lxg.spring5.aopanno"></context:component-scan>
    
</beans>
(2)使用注解创建User和UserProxy对象
(3)在增强类上面添加注解@Aspect

(4)在spring配置文件中开启生成代理对象
<!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 
4、配置不同类型的通知
(1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置。
//增强的类
@Component
@Aspect
public class UserProxy {
    //前置通知
    //@Before注解表示该方法是一个前置通知
    @Before("execution(* com.lxg.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before...");
    }
    //后置通知
    //最终通知
    //@After注解表示该方法是一个后置通知
    @After("execution(* com.lxg.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after...");
    }
    //返回通知
    //@AfterReturning注解表示该方法是一个返回通知
    @AfterReturning("execution(* com.lxg.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning...");
    }
    //异常通知
    //@AfterThrowing注解表示该方法是一个异常通知
    @AfterThrowing("execution(* com.lxg.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing...");
    }
    //环绕通知
    //@Around注解表示该方法是一个环绕通知
    @Around("execution(* com.lxg.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕之前...");
        //被增强的方法执行
        pjp.proceed();
        System.out.println("环绕之后...");
    }
} 
5、相同的切入点抽取
//相同切入点抽取
//定义切入点,通知增强目标类的哪些方法
@Pointcut("execution(*com.lxg.spring5.aopanno.User.add(..))")
public void pointDemo(){}
6、有多个增强类对同一个方法进行增强,设置增强类优先级
(1)在增强类上面添加注解@Order(数字类型值),值越小,优先级越高
7、完全使用注解开发
(1)创建配置类,不需要xml配置文件
@Configuration//声明为配置类
@ComponentScan("com.lxg.spring5.aopanno")//扫描注解
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
} 
@EnableAspectJAutoProxy注解等同于在xml中配置aspectj-autoproxy,表示开启spring对注解AOP的支持,proxyTargClass=true表示强制使用cglib代理方式。 

2.6、AOP操作(Aspect配置文件)

1、创建两个类,增强类和被增强类,创建方法
2、在Spring配置文件中创建两个类对象
<!--创建对象-->
    <bean id="book" class="com.lxg.spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.lxg.spring5.aopxml.BookProxy"></bean>
3、在Spring配置文件中配置切入点
<!--配置aop增强-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="p" expression="execution(* com.lxg.spring5.aopxml.Book.buy(..))"/>
        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上-->
            <!--把before方法配置到切入点p上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config> 

五、jdbcTemplate(概念和准备)

1、什么是JdbcTemplate

1、Spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库的操作 

2、准备工作

1、引入相关依赖 
2、在spring配置文件中配置数据库连接池
<!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://192.168.31.1:3306/bjpowernode" />
        <property name="username" value="root" />
        <property name="password" value="623718" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean> 
3、配置JdbcTemplate对象,注入DataSource
 <!--创建JdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean> 
4、创建service类,创建dao类,在dao注入jdbcTemplate对象
配置文件:
<!--开始组件扫描-->
    <context:component-scan base-package="com.lxg.spring5"></context:component-scan>
    
@Service
public class BookService {
    //注入dao
    @Autowired
    private BookDao bookDao;
}

@Repository
public class BookDaoImpl implements BookDao {
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

} 

3、jdbcTemplate 操作数据库(添加)

3.1、对应数据库创建出实体类

public class User {
    private String useId;
    private String userName;
    private String ustatus;

    public String getUseId() {
        return useId;
    }

    public void setUseId(String useId) {
        this.useId = useId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUstatus() {
        return ustatus;
    }

    public void setUstatus(String ustatus) {
        this.ustatus = ustatus;
    }
} 

3.2、编写service和dao

1、在dao进行数据库添加操作

2、调用JdbcTemplate对象里面的update方法实现添加操作

  • 有两个参数
  • 第一个参数:sql语句
  • 第二个参数:可变参数,设置sql语句值
@Repository
public class BookDaoImpl implements BookDao {
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Book book) {
        //1、创建sql语句
        String sql = "insert into t_book values(?,?,?)";
        //2、调用方法实现
        Object[] args = {book.getBookId(), book.getBookName(),book.getBookAuthor()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println("添加了"+update+"条数据");
    }
} 

3、测试类

@Test
public void testJdbcTemplate() {
    ApplicationContext context =
            new ClassPathXmlApplicationContext("bean1.xml");
    BookService bookService = context.getBean("bookService", BookService.class);
    Book book = new Book();
    book.setBookId("6");
    book.setBookName("Spring5");
    book.setBookAuthor("lxg");
    bookService.addBook(book);
} 

4、jdbcTemplate操作数据库(修改和删除)

@Override
public void bookupdate(Book book) {
    String sql= "update t_book set bookName=?,bookAuthor=? where bookId=?";
    Object[] args = {book.getBookName(),book.getBookAuthor(),book.getBookId()};
    int update = jdbcTemplate.update(sql, args);
    System.out.println("更新了"+update+"条数据");
}

@Override
public void bookdelete(String id) {
    String sql= "delete from t_book where bookId=?";
    int update = jdbcTemplate.update(sql, id);
    System.out.println("删除了"+update+"条数据");
} 

测试:

 @Test
    public void testJdbcTemplate() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        //添加
//        Book book = new Book();
//        book.setBookId("6");
//        book.setBookName("Spring5");
//        book.setBookAuthor("lxg");
//        bookService.addBook(book);
        //修改
//        Book book1 = new Book();
//        book1.setBookId("5");
//        book1.setBookName("web");
//        book1.setBookAuthor("lxg");
//        bookService.updateBook(book1);
        //删除
       bookService.deleteBook("5");
    } 

5、jdbcTemplate操作数据库(查询)

5.1、查询返回某个值

1、查询表里面有多少条记录,返回是某个值

2、使用JdbcTemplate实现查询返回某个值

  • 两个参数
  • 第一个参数,sql语句
  • 第二个参数,返回类型Class
//查询表记录数
@Override
public int findCount() {
    String sql = "select count(*) from t_book";
    Integer count= jdbcTemplate.queryForObject(sql, Integer.class);
    return count;
} 

3、测试

//查询表中记录数
int count= bookService.getCount();
System.out.println(count); 

5.2、查询返回对象

1、场景:查询图书详情

2、JdbcTemplate实现查询返回对象

  • 有三个参数
  • 第一个参数,sql语句
  • 第二个参数:RowMapper,是接口,针对返回不同类型数据,使用这个接口里面的实现类完成数据封装
  • 第三个参数:sql语句值
//查询返回对象
@Override
public Book findBook(String id) {
    String sql = "select * from t_book where bookId=?";
    Book book = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Book>(Book.class),id);
    return book;
} 

5.3、查询返回集合

1、场景:查询图书列表分页...

2、调用jdbcTemplate方法实现查询返回集合

@Override
public List<Book> findBooks() {
    String sql = "select * from t_book";
    List<Book> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Book>(Book.class));
    return list;
} 

6、jdbcTemplate操作数据库(批量操作)

1、批量操作:操作表里面多条记录

6.1、实现批量添加操作

  • 有两个参数
  • 第一个参数:sql语句
  • 第二个参数:List集合,添加多条记录数据
//批量添加
@Override
public void addBatch(List<Object[]> batchArgs) {
    String sql = "insert into t_book values(?,?,?)";
    int[] ints =  jdbcTemplate.batchUpdate(sql,batchArgs);
    System.out.println("添加了"+ints.length+"条数据");
} 
//批量添加
List<Object[]> batchArgs = new ArrayList<>();
Object[] args1 = {"7","Spring5","lxg"};
Object[] args2 = {"8","Spring5","lxg"};
Object[] args3 = {"9","Spring5","lxg"};
batchArgs.add(args1);
batchArgs.add(args2);
batchArgs.add(args3);
bookService.addBooks(batchArgs); 

6.2、实现批量修改操作

//批量更新
@Override
public void updateBatch(List<Object[]> batchArgs) {
    String sql = "update t_book set bookName=?,bookAuthor=? where bookId=?";
    int[] ints =  jdbcTemplate.batchUpdate(sql,batchArgs);
    System.out.println("更新了"+ints.length+"条数据");
} 
//批量更新
List<Object[]> batchArgs1= new ArrayList<>();
Object[] args1 = {"java","lxg","7"};
Object[] args2 = {"java","lxg","8"};
Object[] args3 = {"java","lxg","9"};
batchArgs1.add(args1);
batchArgs1.add(args2);
batchArgs1.add(args3);
bookService.updateBooks(batchArgs1); 

6.3、实现批量删除操作

//批量删除
@Override
public void deleteBatch(List<Object[]> batchArgs) {
    String sql = "delete from t_book where bookId=?";
    int[] ints =  jdbcTemplate.batchUpdate(sql,batchArgs);
    System.out.println("删除了"+ints.length+"条数据");
} 
//批量删除
List<Object[]> ids = new ArrayList<>();
Object[] id1 = {"7"};
Object[] id2 = {"8"};
Object[] id3 = {"9"};
ids.add(id1);
ids.add(id2);
ids.add(id3);
bookService.deleteBooks(ids); 

六、Spring5框架的新功能

1、整个Spring框架的代码基于Java8,运行时兼容jdk9,许多不建议的类和方法在代码库中删除。

2、Spring5.0框架自带了通用的日志封装

1、Spring5已经移除了log4jConfigListener,官方建议使用Log4j2
2、Spring框架中整合Log4j2
*第一步:引入jar包
*第二步:创建log4j2配置文件 

3、Spring框架核心容器支持@Nullable注解

1、@Nullable注解可以使用在方法上面,属性上面,参数上面,表示方法可以方法返回值可以为空,属性值可以为空,参数值可以为空。 

4、Spring5核心容器支持函数式风格

//函数式风格创建对象,交给Spring管理
@Test
public void testAccount4(){
    //创建GenericApplicationContext对象
    GenericApplicationContext context =
            new GenericApplicationContext();
    //调用context的方法对象注册
    context.refresh();//把内容清空进行注册
    context.registerBean("user1",User.class, () -> new User());
    //获取在Spring注册的对象
    //User user =(User)context.getBean("com.lxg.spring5.test.User");
    User user1 = (User)context.getBean("user1");
    //System.out.println(user);
    System.out.println(user1);
} 

5、Spring5支持整合JUnit5

1、整合Junit4
*第一步:引入Spring相关针对的依赖
spring-test依赖 
@RunWith(SpringJUnit4ClassRunner.class)//单元测试框架
@ContextConfiguration("classpath:bean1.xml")//加载配置文件
public class JTest4 {
    @Autowired
    private UserService userService;
    @Test
    public void test1(){
        userService.transfer();
    }

} 
2、Spring5整合Junit5
*第一步:引入JUnit5jar包 
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {
    @Autowired
    private UserService userService;

    @Test
    public void test(){
        userService.transfer();
    }
} 

使用复合注解替代上面两个注解

@SpringJUnitConfig(locations = "classpath:bean1.xml") 

6、WebFulx介绍

7、响应式编程

8、WebFlux执行流程和核心API

9、SpringWebFlux(基于注解编程模型)

10、SpringWebFlux(基于函数式编程模型)

七、事务

1、事物概念

1.1、什么是事务?

1、事务是数据库操作最基本的单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作就都失败。
2、典型场景:银行转账
*lucy转账100元要给mary
*lucy少100元,mary多100元 

1.2、事物的四个特性(ACID)

  1. 原子性:不可分割
  2. 一致性:操作前后总量不变,守恒
  3. 隔离性:多事务之间互不干扰
  4. 持久性:表中数据发生变化是永久的

2、事务操作(搭建事务操作环境)

1、创建数据库表,添加记录

2、创建service,搭建dao,完成对象创建和注入关系

(1)service注入dao,在dao注入JdbcTemplate,在JdbcTemplate注入DataSource

@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

}

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

} 

3、在dao创建两个方法:多钱和少钱,在service创建转账的方法

//多钱
//lucy转账100给marry
@Override
public void addMoney() {
    String sql = "update t_account set money = money + ? where username = ?";
    jdbcTemplate.update(sql, "marry");
}

//少钱
@Override
public void reduceMoney() {
    String sql = "update t_account set money = money -? where username = ?";
    jdbcTemplate.update(sql, "lucy");
} 
@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;
    //转账
    public void transfer() {
        //转出
       userDao.reduceMoney();
        //转入
        userDao.addMoney();
    }
} 

4、上面代码正常执行没有问题,但是如果在执行过程中有异常就会有问题

//转账
public void transfer() {
    //转出
   userDao.reduceMoney();
   //模拟异常
   int i = 1/0;
    //转入
    userDao.addMoney();
} 

lucy少了钱但是marry钱没增加

1、怎么解决这个问题?
*使用事务进行解决
2、事务操作过程
1、开启事务
2、执行业务操作
3、没有异常,提交事务
4、出现异常,回滚事务 

3、事务操作(Spring事务管理介绍)

1、事务添加到JavaEE三层结构里面Service层(业务逻辑层)

2、在Spring进行事务管理操作

  • 有两种方式:编程式事务管理和声明式事务管理(常用)

3、声明式事务管理

  • 基于注解方式(多用)
  • 基于xml配置文件方式

4、在Spring进行声明式事务管理,底层使用AOP

5、Spring事务管理的API

1、提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类 

3.1、事务操作(注解声明式事务管理)

1、在Spring配置文件中配置事务管理器

<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean> 

2、在Spring配置文件中开启事务注解

1、在spring配置文件中引入名称空间tx
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schem/tx/spring-tx.xsd"> 
2、开启事务注解
<!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> 
3、在service类上面(获取service类里面方法上面)添加事务注解
@Transactional,这个注解可以添加在类上面,也可以添加到方法上面
如果把这个注解添加到类上面,这个类中的所有方法都添加事务
如果把这个注解添加到方法上面,为这个方法添加事务 

3.2、事务操作(声明式事务管理参数配置)

1、在service类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数

2、proagation:事务传播行为

(1)多事务方法之间进行调用,这个过程中事务是如何管理的。

掌握前两种即可

3、ioslation:事务隔离级别

1、事务里有个特性为隔离性,多事务操作之间不会产生影响,不考虑隔离线产生很多问题
2、有三个读的问题:脏读、不可重复读、虚(幻)读
3、脏读:一个未提交的事务读取到另一个未提交事务的数据
4、不可重复读:一个未提交事务读取到另一个已提交的事务的数据
5、一个未提交事务读取到另一个提交事务添加的数据
6、解决:通过设置隔离级别,解决读的问题
默认可重复读 
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ) 

4、timeout:超时时间

1、事务需要在一定的事间内进行提交,如果不提交进行回滚
2、默认值是-1,不回滚,设置时间以秒单位进行计算 

5、reafOnly:是否只读

1、读:查询操作,写:添加修改删除操作
2、readOnly默认值false,表示可以查询,也可以增删改
3、设置为true,则只能查询 

6、rollbackFor:回滚

1、设置出现哪些异常进行事务回滚 

7、noRollbackFor:不回滚

设置出现哪些异常不进行事务回滚 

3.3、事务操作(XML声明式事务管理)

1、在Spring配置文件中进行配置

  • 第一步配置事务管理器
  • 第二步配置通知
  • 第三步配置切入点和切面
<!--配置通知-->
    <tx:advice id="txAdvice">
        <!--配置事务参数-->
        <tx:attributes>
            <tx:method name="tansfer" propagation="REQUIRED" />
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>

    <!--配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="txPointcut" expression="execution(* com.lxg.spring5.service.UserService.*(..))"></aop:pointcut>
        <!--配置切面-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
    </aop:config> 

3.4、事务操作(完全注解声明式事务管理)

@Configuration//配置类
@ComponentScan(basePackages = "com.lxg")//组件扫描
@EnableTransactionManagement//开启事务管理

public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDuridDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/bjpowernode");
        dataSource.setUsername("root");
        dataSource.setPassword("623718");
        return dataSource;
    }
    //创建jdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        //到IOC容器中根据类型找到dataSource对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

} 

本文作者:_xiaolin

本文链接:https://www.cnblogs.com/SilverStar/p/17415624.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   _xiaolin  阅读(0)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起