spring

这个学习内容是借鉴的,做笔记是为了不让我遗忘太快。
里面的过程和代码都已经自己实现过了,同时有一些也加了自己的理解。

文章目录

1.程序的耦合和解耦

耦合: 程序间的依赖关系.在开发中,应该做到解决编译期依赖,即编译期不依赖,运行时才依赖`.

解耦的思路: 使用反射来创建对象,而避免使用new关键字,并通过读取配置文件来获取要创建的对象全限定类名.

解耦实例1:JDBC驱动注册

JDBC操作中注册驱动时,我们不使用DriverManagerregister方法,而采用Class.forName("驱动类全类名")的方式。

public static void main(String[] args) throws SQLException, ClassNotFoundException {
	//注册驱动的两种方式
	// 1. 创建驱动类的实例 
	    //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
	// 2. 通过反射加载驱动类
	Class.forName("com.mysql.jdbc.Driver");		// 实际开发中此类名从properties文件中读取
	
	//...后续操作
}

即使驱动类不存在,在编译时也不会报错,解决了编译器依赖。

解耦实例2:UI层,Service层,Dao层的调用

在Web项目中,UI层,Service层,Dao层之间有着前后调用的关系。

public class Client {  //在业务层
    public static void main(String[] args) {
        IAccountService as = new AccountServiceImpl();  // 在业务层要调用持久层的接口和实现类
        as.saveAccount();
    }
}

业务层依赖持久层的接口和实现类,若编译时不存在没有持久层实现类,则编译将不能通过,这构成了编译期依赖。

工厂模式解耦:

在实际开发中可以把三层的对象的全类名都使用配置文件保存起来,当启动服务器应用加载的时候,创建这些对象的实例并保存在容器中(单例的)。 在获取对象时,不使用new的方式,而是直接从容器中获取,这就是工厂设计模式。

配置文件:bean.properties

accountService=com.service.impl.AccountServiceImpl
accountDao=com.dao.impl.AccountDaoImpl

BeanFactory.class : (多例的代码)

ublic class BeanFactory {
    private static Properties props;

    //使用静态代码块为Properties对象赋值
    static{
        try {
            props = new Properties();   //实例化对象
            //获取properties文件的流对象
            InputStream in =          	         BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
        }catch (Exception e){
            throw new ExceptionInInitializerError("初始化properties失败");
        }
    }

    /**
     * 根据Bean的名称获取bean开发
     */
    public static Object getBean(String beanName){
        Object bean = null;
        try {
            String beanPath = props.getProperty(beanName);
            bean = Class.forName(beanPath).newInstance();
        }catch(Exception e){
            e.printStackTrace();
        }
        return bean;
    }
}

这样子,在Client.class在初始化接口实现类时就不用new了。

在其他需要初始化接口实现类时也不用new了。如下:

public class Client {
    public static void main(String[] args) {
        //IAccountService as = new AccountServiceImpl();
        IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
        as.saveAccount();
    }
}

多例与单例

多例:

使用上述所说的BeanFactory.class,那么就会产生多例。例如:

public class Client {
    public static void main(String[] args) {
        //IAccountService as = new AccountServiceImpl();
        for(int i=0;i<5;i++){
        IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
            System.out.println(as);
        }
    }
}

此时会产生五个对象,每个对象对应的内存不同。
对象被创建多次,执行效率没有单例对象高。

单例:

只被创建一次,从而类中的成员也就只会初始化一次。

BeanFactory.class得改:

public class BeanFactory {
    private static Properties props;

    //定义一个Map,用于存放我们要创建的对象。我们把它称为容器
    private static Map<String,Object> beans;

    //使用静态代码块为Properties对象赋值
    static{
        try {
            props = new Properties();   //实例化对象
            //获取properties文件的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            //实例化容器
            beans = new HashMap<String, Object>();
            //取出配置文件中所有的key。   Enumeration是枚举类型
            Enumeration keys = props.keys();
            //遍历枚举
            while(keys.hasMoreElements()){
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器之中
                beans.put(key,value);
            }
        }catch (Exception e){
            throw new ExceptionInInitializerError("初始化properties失败");
        }
    }

    public static Object getBean(String beanName){
        return beans.get(beanName);    //对象已经创建放在容器中,这样就会放回以前创建的对象
    }
}

2.控制反转-Inversion Of Control(IOC)

上一小节解耦的思路有 2 个问题:

1*、对象存哪去?*
分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。
到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。
所以我们的答案就是在应用加载时,创建一个 Map,用于存放三层对象。
我们把这个 map 称之为容器

2、什么是工厂?
工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。

原来:
我们在获取对象时,都是采用 new 的方式。是主动的。

在这里插入图片描述
现在:
我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。

这种被动接收的方式获取对象的思想就是控制反转,它是 spring 框架的核心之一。

控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫依赖查找(Dependency Lookup)。

IoC 的作用

削减计算机程序的耦合(解除我们代码中的依赖关系)。

3.使用spring的IOC解决程序耦合

1.准备工作:pom.xml:

<dependencies>
    	<!-- 引入-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
</dependencies>

创建三层接口类和实现类的结构如下,模拟一个保存账户的服务。

在这里插入图片描述

2.配置bean: 在类的根路径下的resource目录下创建bean.xml文件,把对象的创建交给spring来管理.
每个<bean>标签对应一个类,其class属性为该类的全类名,id属性为该类的id,在spring配置中,通过id获取类的对象。

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd">
 
     <!--把对象的创建交给spring来管理-->
     <bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>
     <bean id="accountDao" class="com.dao.impl.AccountDaoImpl"></bean>
 </beans>

3.在表现层文件Client.java中通过容器创建对象.通过核心容器的getBean()方法获取具体对象.

public class Client {
     public static void main(String[] args) {
         // 获取核心容器对象
         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
         // 根据id获取Bean对象
         IAccountService as  = (IAccountService)ac.getBean("accountService");
         IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);  //后面这个参数相当于强制转换
         // 执行as,adao的具体方法
         // ...
     }
 }

ApplicationContext是一个接口,它的实现类常用的有:ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,AnnotationConfigApplicationContext。

1.ClassPathXmlApplicationContext: 它是从类的根路径下加载配置文件
2.FileSystemXmlApplicationContext: 它是从磁盘路径上加载配置文件
3.AnnotationConfigApplicationContext: 读取注解创建容器

BeanFactory 和 ApplicationContext的区别:

BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。

核心容器的两个接口引发出的问题:

​ ApplicationContext: 单例对象适用 一般采用此接口 有多例的功能
​ 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配 置文件中配置的对象。

​ BeanFactory: 多例对象使用
​ 它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时 候才真正的创建对象。

4.IOC 中 bean 标签和管理对象细节

1.实例化 Bean 的三种方式

1.使用默认无参构造函数创建对象: 默认情况下会根据默认无参构造函数来创建类对象,若Bean类中没有默认无参构造函数,将会创建失败.

<bean id="accountService" 
	class="com.service.impl.AccountServiceImpl"></bean>

2.使用普通工厂的方法创建对象 (使用某个类的方法创建对象,并存入spring容器中)。

创建普通工厂如下:

/**
* 模拟一个实例工厂,创建业务层实现类
* 此工厂创建对象,必须现有工厂实例对象,再调用方法
*/
public class InstanceFactory {
	public IAccountService createAccountService(){
		return new AccountServiceImpl();    
	}
}

先创建普通工厂对象instanceFactory,通过调用其createAccountService()方法创建对象,涉及到<bean>标签的属性:

  1. factory-bean属性: 指定普通工厂的id

  2. factory-method属性: 指定普通工厂中生产对象的方法

    <bean id="instancFactory" class="com.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instancFactory" factory-method="createAccountService"></bean>
    

测试类无改变:

public class Client {
    public static void main(String[] args) {
        ApplicationContext ac  = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService)  ac.getBean("accountService");
        as.saveAccount();
    }
}

3.使用工厂的静态方法创建对象:

创建工厂如下:

// 静态工厂,其静态方法用于创建对象
public class StaticFactory {
	public static IAccountService createAccountService(){
		return new AccountServiceImpl();
	}
}

使用StaticFactory类中的静态方法createAccountService创建对象,涉及到标签的属性:
1.id属性: 指定对象在容器中的标识,用于从容器中获取对象
2.class属性: 指定静态工厂的全类名
3.factory-method属性: 指定生产对象的静态方法

<bean id="accountService" class="com.factory.StaticFactory" factory-method="createAccountService"></bean>

2.bean的作用范围和生命周期

1.单例对象: scope=“singleton”
作用范围:每个应用只有一个该对象的实例,它的作用范围就是整个应用
生命周期:单例对象的创建与销毁 和 容器的创建与销毁时机一致
对象出生:当应用加载,创建容器时,对象就被创建
对象活着:只要容器存在,对象一直活着
对象死亡:当应用卸载,销毁容器时,对象就被销毁

2.多例对象: scope=“prototype”
作用范围:每次访问对象时,都会重新创建对象实例.
生命周期:多例对象的创建与销毁时机不受容器控制
对象出生:当使用对象时,创建新的对象实例
对象活着:只要对象在使用中,就一直活着
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了

<!-- 单例对象,默认为单例
<bean id="accountService" 
      class="com.service.impl.AccountServiceImpl" scope="singleton"></bean> -->

<!-- 多例对象 -->
<bean id="accountService" class="com.service.impl.AccountServiceImpl" scope="prototype"></bean>

3.bean标签

作用:
配置托管给spring的对象,默认情况下调用类的无参构造函数,若果没有无参构造函数则不能创建成功

属性:
id: 指定对象在容器中的标识,将其作为参数传入getBean()方法可以获取获取对应对象.
class: 指定类的全类名,默认情况下调用无参构造函数
scope: 指定对象的作用范围,可选值如:singleton: 单例对象,默认值 prototype: 多例对象
request: 将对象存入到web项目的request域中
session: 将对象存入到web项目的session域中
global session: 将对象存入到web项目集群的session域中,若不存在集群,则global session相当于session
init-method:指定类中的初始化方法名称,在对象创建成功之后执行
destroy-method:指定类中销毁方法名称,对prototype多例对象没有作用,因为多例对象的销毁时机不受容器控制

5.依赖注入

IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的。比如对象A需要操作数据库,以前我们总是要在A中自己编写代码来获得一个Connection对象,有了 spring我们就只需要告诉spring,A中需要一个Connection,至于这个Connection怎么构造,何时构造,A不需要知道。在系统运行时,spring会在适当的时候制造一个Connection,然后像打针一样,注射到A当中,这样就完成了对各个对象之间关系的控制。A需要依赖 Connection才能正常运行,而这个Connection是由spring注入到A中的,依赖注入的名字就这么来的。

依赖注入的方法

因为我们是通过反射的方式来创建属性对象的,而不是使用new关键字,因此我们要指定创建出对象各字段的取值.

1.使用构造函数注入(不常用)

通过类默认的构造函数来给创建类的字段赋值,相当于调用类的构造方法.

涉及的标签: 用来定义构造函数的参数,其属性可大致分为两类:

寻找要赋值给的字段
index: 指定参数在构造函数参数列表的索引位置
type: 指定参数在构造函数中的数据类型
name: 指定参数在构造函数中的变量名,最常用的属性
指定赋给字段的值
value: 给基本数据类型和String类型赋值
ref: 给其它Bean类型的字段赋值,ref属性的值应为配置文件中配置的Bean的id

public class AccountServiceImpl implements IAccountService {
    //如果是经常变化的数据,并不适用于注入的方式
    private String name;
    private Integer age;
    private Date birthday;

    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void saveAccount() {
		System.out.println(name+","+age+","+birthday);
    }
}

<!-- 使用Date类的无参构造函数创建Date对象 -->
<bean id="now" class="java.util.Date" scope="prototype"></bean>

<bean id="accountService" class="com.service.impl.AccountServiceImpl">
	<constructor-arg name="name" value="myname"></constructor-arg>
	<constructor-arg name="age" value="18"></constructor-arg>
	<!-- birthday字段为已经注册的bean对象,其id为now -->
	<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>

弊端:
我们在创建对象时,如果用不到这些数据,也必须提供。

2.使用set方法注入(更常用)

在类中提供需要注入成员属性的set方法,创建对象只调用要赋值属性的set方法.

涉及的标签: ,用来定义要调用set方法的成员. 其主要属性可大致分为两类:

指定要调用set方法赋值的成员字段
name:要调用set方法赋值的成员字段
指定赋给字段的值
value: 给基本数据类型和String类型赋值
ref: 给其它Bean类型的字段赋值,ref属性的值应为配置文件中配置的Bean的id

public class AccountServiceImpl implements IAccountService {

	private String name;
	private Integer age;
	private Date birthday;

	public void setUserName(String name) {
		this.name = name;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public void saveAccount() {
		System.out.println(name+","+age+","+birthday);
	}
}
<!-- 使用Date类的无参构造函数创建Date对象 -->
<bean id="now" class="java.util.Date" scope="prototype"></bean>

<bean id="accountService" class="com.service.impl.AccountServiceImpl">
	<property name="userName" value="myname"></property>  <!--name的值对应setUserName方法-->
	<property name="age" value="21"></property>
	<!-- birthday字段为已经注册的bean对象,其id为now -->
	<property name="birthday" ref="now"></property>
</bean>

优势:
创建对象时没有明确的对象限制,可以直接使用默认构造函数

弊端:
如果某个成员必须有值,则获取对象是有可能set方法没有执行。

3.使用set方法注入集合字段

集合字段及其对应的标签按照集合的结构分为两类: 相同结构的集合标签之间可以互相替换.

只有键的结构:

数组字段: 标签表示集合,标签表示集合内的成员.
List字段: 标签表示集合,标签表示集合内的成员.
Set字段: 标签表示集合,标签表示集合内的成员.
其中,,标签之间可以互相替换使用.

键值对的结构:

Map字段: 标签表示集合,标签表示集合内的键值对,其key属性表示键,value属性表示值.
Properties字段: 标签表示集合,标签表示键值对,其key属性表示键,标签内的内容表示值.
其中,标签之间,,标签之间可以互相替换使用.

下面使用set方法注入各种集合字段

public class AccountServiceImpl implements IAccountService {
	// 集合字段
	private String[] myArray;
	private List<String> myList;
	private Set<String> mySet;
	private Map<String,String> myMap;
	private Properties myProps;

	// 集合字段的set方法
	public void setMyStrs(String[] myArray) {
		this.myArray = myArray;
	}
	public void setMyList(List<String> myList) {
		this.myList = myList;
	}
	public void setMySet(Set<String> mySet) {
		this.mySet = mySet;
	}
	public void setMyMap(Map<String, String> myMap) {
		this.myMap = myMap;
	}
	public void setMyProps(Properties myProps) {
		this.myProps = myProps;
	}
	
	@Override
	public void saveAccount() {
		System.out.println(Arrays.toString(myArray));
		System.out.println(myList);
		System.out.println(mySet);
		System.out.println(myMap);
		System.out.println(myProps);
	}
}

<bean id="accountService" class="com.service.impl.AccountServiceImpl3">
	<property name="myStrs">
		<array>
			<value>value1</value>
			<value>value2</value>
			<value>value3</value>
		</array>
	</property>

	<property name="myList">
		<list>
			<value>value1</value>
			<value>value2</value>
			<value>value3</value>
		</list>
	</property>

	<property name="mySet">
		<set>
			<value>value1</value>
			<value>value2</value>
			<value>value3</value>
		</set>
	</property>

	<property name="myMap">
		<map>
			<entry key="key1" value="value1"></entry>
			<entry key="key2">
				<value>value2</value>
			</entry>	
		</map>
	</property>

	<property name="myProps">
		<props>
			<prop key="key1">value1</prop>
			<prop key="key2">value2</prop>
		</props>
	</property>
</bean>

6.使用注解实现IOC

使用注解实现IOC,要将注解写在类的定义中

1.spring的半注解配置

半注解配置下,spring容器仍然使用ClassPathXmlApplicationContext类从xml文件中读取IOC配置,同时在xml文件中告知spring创建容器时要扫描的包.

例如,使用半注解模式时,后面简单实例中的beans.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知spring在创建容器时要扫描的包,配置此项所需标签不在beans的约束中,而在一个名为context的名称空间和约束中-->
    <context:component-scan base-package="com"></context:component-scan>
</beans>

然后将spring注解加在类的定义中。

2.大体了解常用注解与bean.xml的联系:

/*曾经XML的配置:
 *  <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *        scope=""  init-method="" destroy-method="">
 *      <property name=""  value="" | ref=""></property>
 *  </bean>
 *
 * 用于创建对象的
 *      他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
 *      Component:用于把当前类对象存入spring容器中
 *
 *      Controller:一般用在表现层
 *      Service:一般用在业务层
 *      Repository:一般用在持久层
 *      以上三个注解他们的作用和属性与Component是一模一样。
 *      他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
 *
 * 用于注入数据的
 *      他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的
 *      Autowired:
 *          作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *                如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
 *                如果Ioc容器中有多个类型匹配时:
 *
 *      Qualifier:
 *          作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以(稍后我们讲)
 *         
 *      Resource
 *          作用:直接按照bean的id注入。它可以独立使用
 *
 *      以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
 *      另外,集合类型的注入只能通过XML来实现。
 *
 *      Value:用于注入基本类型和String类型的数据
 *
 * 用于改变作用范围的
 *      他们的作用就和在bean标签中使用scope属性实现的功能是一样的
 *      Scope:用于指定bean的作用范围
 *
 * 和生命周期相关 (了解)
 *      他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的
 *      PreDestroy
 *          作用:用于指定销毁方法
 *      PostConstruct
 *          作用:用于指定初始化方法
 */

3.常用注解细节

1.用于创建对象的注解

1.@Component: 把当前类对象存入spring容器中,其属性如下:
value: 用于指定当前类的id. 不写时默认值是当前类名,且首字母改小写。
2.@Controller: 将当前表现层对象存入spring容器中。
3.@Service: 将当前业务层对象存入spring容器中。
4.@Repository: 将当前持久层对象存入spring容器中。

@Controller,@Service,@Repository注解的作用和属性与@Component是一模一样的,可以相互替代,它们的作用是使三层对象的分别更加清晰.

2.用于注入数据的注解

这些注解的作用相当于bean.xml中的标签.

1.@Autowired: 自动按照成员变量类型注入.
1.注入过程:
1.当spring容器中有且只有一个对象的类型与要注入的类型相同时,注入该对象.
2.当spring容器中有多个对象类型与要注入的类型相同时,使用要注入的变量名作为bean的id,在spring 容器查找,找 到则注入该对象.找不到则报错.
2.出现位置: 既可以在变量上,也可以在方法上
3.细节: 使用注解注入时,set方法可以省略

2.@Qualifier: 在自动按照类型注入的基础之上,再按照bean的id注入.
1.出现位置: 既可以在变量上,也可以在方法上.注入变量时不能独立使用,必须和@Autowire一起使用; 注入方法时可以 独立使用.
2.属性: value: 指定bean的id

@Component("abc")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    @Qualifier("accountDao1")    //注入bean的id为accountDao1的对象
    private IAccountDao accountDao;
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

3.@Resource: 直接按照bean的id注入,它可以独立使用.独立使用时相当于同时使用和两个注解@Autowired@Qualifier。
1.属性: name: 指定bean的id

@Component("abc")
public class AccountServiceImpl implements IAccountService {

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao1")
    private IAccountDao accountDao;
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
另外,集合类型的注入只能通过xml来实现。

4.@Value: 注入基本数据类型和String类型数据。
1.属性: value: 用于指定数据的值,可以使用el表达式(${表达式})

3.用于改变作用范围的注解

这些注解的作用相当于bean.xml中的标签的scope属性.

@Scope: 指定bean的作用范围
属性:
value: 用于指定作用范围的取值,常用:“singleton”,“prototype”。
单例(默认) 多例

@Component("abc")
@Scope("prototype")
public class AccountServiceImpl implements IAccountService {
    
    @Resource(name = "accountDao1")
    private IAccountDao accountDao;
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

4. 和生命周期相关的注解

这些注解的作用相当于bean.xml中的<bean>标签的init-methoddestroy-method
属性:
1.@PostConstruct: 用于指定初始化方法
2.@PreDestroy: 用于指定销毁方法

4.纯注解配置

在纯注解配置下,我们用配置类替代bean.xml, spring容器使用AnnotationApplicationContext类从spring配置类中读取IOC配置

1.纯注解配置下的注解

@Configuration: 用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解.获取容器时需要使用 AnnotationApplicationContext(有@Configuration注解的类.class).
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

@ComponentScan: 指定spring在初始化容器时要扫描的包,作用和bean.xml 文件中 <context:component-scan base-package=“要扫描的包名”/> 是一样的. 其属性如下:
basePackages: 用于指定要扫描的包,是value属性的别名

@ComponentScan("com")

@Bean: 该注解只能写在方法上,表明使用此方法创建一个对象,并放入spring容器,其属性如下:
name: 指定此方法创建出的bean对象的id
细节: 使用注解配置方法时,如果方法有参数,Spring框架会到容器中查找有没有可用的bean对象,查找的方式与@Autowired注解时一样的.

@PropertySource: 用于加载properties配置文件中的配置.例如配置数据源时,可以把连接数据库的信息写到properties配 置文件中,就可以使用此注解指定properties配置文件的位置,其属性如下:
value: 用于指定properties文件位置.如果是在类路径下,需要写上"classpath:"

@PropertySource("classpath:jdbcConfig.properties")

@Import: 用于导入其他配置类.当我们使用@Import注解之后,有@Import注解的类就是父配置类,而导入的都是子配置类. 其属性如下:
value: 用于指定其他配置类的字节码

2.实例: 使用纯注解配置实现数据库CRUD

​ 1.项目结构: 其中包com存放业务代码,包config存放配置类。
在这里插入图片描述

​ 2.包com存放业务代码,其中dao层实现类和service层实现类的代码如下:
​ dao层实现类:

@Repository("aacountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;


    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    public Account findAccountById(Integer id) {
        try{
            return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer id) {
        try{
            runner.update("delete from account where id=?",id);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

​ service层实现类:

@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

3.包config存放配置类,其中配置类代码如下:

​ 其中SpringConfigration类为主配置类,内容如下:

//@Configuration					// 说明此类为配置类
@ComponentScan("com")	// 指定初始化容器时要扫描的包
@Import(JdbcConfig.class)		// 引入JDBC配置类
@PropertySource("classpath:jdbcConfig.properties") //指定配置文件的路径。在jdbcConfig需要
public class SpringConfiguration {
}

​ 其中jdbcConfig类为JDBC配置类,内容如下:

@Configuration									// 说明此类为配置类
@PropertySource("classpath:jdbc.properties")	// 指定配置文件的路径,关键字classpath表示类路径
public class JdbcConfig {

    @Value("${jdbc.driver}")	// 为driver成员属性注入值,使用el表达式
    private String driver;

    @Value("${jdbc.url}")		// 为url成员属性注入值,使用el表达式
    private String url;

    @Value("${jdbc.username}")	// 为usernamer成员属性注入值,使用el表达式
    private String username;

    @Value("${jdbc.password}")	// 为password成员属性注入值,使用el表达式
    private String password;

    // 创建DBUtils对象
    @Bean(name="runner")	// 此将函数返回的bean对象存入spring容器中,其id为runner
    @Scope("prototype")		// 说明此bean对象的作用范围为多例模式,以便于多线程访问
    public QueryRunner createQueryRunner(@Qualifier("ds") DataSource dataSource){
		// 为函数参数datasource注入id为ds的bean对象
        return new QueryRunner(dataSource);
    }

    // 创建数据库连接池对象
    @Bean(name="ds")		// 此将函数返回的bean对象存入spring容器中,其id为ds
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

4.包test存放测试类,实现如下:
AccountServiceTest实现:

public class AccountServiceTest {

    @Test
     public void testFindAll(){
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        List<Account> accounts = as.findAllAccount();
        for(Account account: accounts)
            System.out.println(account);
        }
        
    @Test
    public void testFindOne(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
      IAccountService as = ac.getBean("accountService",IAccountService.class);
      Account account = as.findAccountById(1);
      System.out.println(account);
    }

    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("test");
        account.setMoney(123456f);
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        as.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        Account account = as.findAccountById(4);
        account.setMoney(5324f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        as.deleteAccount(4);
    }

}

7.spring整合junit完成

其他的和上面实例一样,在测试类AccountServiceTest实现不同,如下:(注释为上面被删除的语句)
因为在这个类中,获取容器有太多重复代码了。所以使用spring整合junit完成。

@RunWith(SpringJUnit4ClassRunner.class)  //@RunWith就是一个运行											//器,@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@ContextConfiguration(classes = SpringConfigration.class)
public class AccountServiceTest {
	@Autowired
    private IAccountService as = null;
    
    @Test
     public void testFindAll(){
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
   //     ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
     //   IAccountService as = ac.getBean("accountService",IAccountService.class);
        List<Account> accounts = as.findAllAccount();
        for(Account account: accounts)
            System.out.println(account);
        }

    @Test
    public void testFindOne(){
     //   ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
   //   IAccountService as = ac.getBean("accountService",IAccountService.class);
      Account account = as.findAccountById(1);
      System.out.println(account);
    }

    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("test");
        account.setMoney(123456f);
    //    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
   //     IAccountService as = ac.getBean("accountService",IAccountService.class);
        as.saveAccount(account);
    }

    @Test
    public void testUpdate(){
    //    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
   //     IAccountService as = ac.getBean("accountService",IAccountService.class);
        Account account = as.findAccountById(4);
        account.setMoney(5324f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete(){
    //    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
    //    IAccountService as = ac.getBean("accountService",IAccountService.class);
        as.deleteAccount(4);
    }

}

这样我们在每个Test就不用被注释掉的语句。
这是使用spring整合junit完成。

步骤:

1、导入spring整合junit的jar(坐标)

<dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-test</artifactId>
       <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
</dependency>

2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@Runwith

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = SpringConfigration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")   xml的用法
public class AccountServiceTest {
    .......
}

3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在地位置

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = SpringConfigration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")   xml的用法
public class AccountServiceTest {
    .......
}

当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上

8.代码冗余与装饰器模式

1.代码冗余现象

我们的Service层实现类中的每个方法都要加上事务控制,这样使得每个方法的前后都要加上重复的事务控制的代码,如下:
(这里的事务控制方法不推荐使用,所以省略具体的使用步骤,后面会有更好的方法)

public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;
    private TransactionManager txManager;   //事务控制,自己设计的类

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            List<Account> accounts = accountDao.findAllAccount();
            //3.提交事务
            txManager.commit();
            //4.返回结果
            return accounts;
        }catch (Exception e){
            //5.回滚操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.释放连接
            txManager.release();
        }

    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            Account account = accountDao.findAccountById(accountId);
            //3.提交事务
            txManager.commit();
            //4.返回结果
            return account;
        }catch (Exception e){
            //5.回滚操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.释放连接
            txManager.release();
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.saveAccount(account);
            //3.提交事务
            txManager.commit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void updateAccount(Account account) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.updateAccount(account);
            //3.提交事务
            txManager.commit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void deleteAccount(Integer acccountId) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.deleteAccount(acccountId);
            //3.提交事务
            txManager.commit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作

            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //2.3转出账户减钱
            source.setMoney(source.getMoney()-money);
            //2.4转入账户加钱
            target.setMoney(target.getMoney()+money);
            //2.5更新转出账户
            accountDao.updateAccount(source);

            int i=1/0;

            //2.6更新转入账户
            accountDao.updateAccount(target);
            //3.提交事务
            txManager.commit();

        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
            e.printStackTrace();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }
}

我们发现出现了两个问题:

  1. 业务层方法变得臃肿了,里面充斥着很多重复代码.
  2. 业务层方法和事务控制方法耦合了. 若提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码.

因此我们引入了装饰模式解决代码冗余和耦合现象.

2.解决代码冗余的思路: 装饰模式和动态代理

1.动态代理的写法

动态代理:
特点:字节码随用随创建,随用随加载
作用:不修改源码的基础上对方法增强

常用的动态代理分为两种

  1. 基于接口的动态代理,使用JDK 官方的 Proxy 类,要求被代理者至少实现一个接口

  2. 基于子类的动态代理,使用第三方的 CGLib库,要求被代理类不能是final类.

    在这里我们使用基于接口的动态代理
    基于接口的动态代理:
    涉及的类:Proxy
    提供者:JDK官方
    如何创建代理对象:
    使用Proxy类中的newProxyInstance方法
    创建代理对象的要求:
    被代理类最少实现一个接口,如果没有则不能使用
    newProxyInstance方法的参数:
    ClassLoader:类加载器
    它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。
    Class[]:字节码数组
    它是用于让代理对象和被代理对象有相同方法。固定写法。
    InvocationHandler:用于提供增强的代码
    它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。此接口的实现类都是谁用谁写。

写法如下:

接口名 新对象名 = (接口名)Proxy.newProxyInstance(
    被代理的对象.getClass().getClassLoader(),	// 被代理对象的类加载器,固定写法
    被代理的对象.getClass().getInterfaces(),	// 被代理对象实现的所有接口,固定写法
    new InvocationHandler() {	// 匿名内部类,通过拦截被代理对象的方法来增强被代理对象
        /* 被代理对象的任何方法执行时,都会被此方法拦截到
        	其参数如下:
                proxy: 代理对象的引用,不一定每次都用得到
                method: 被拦截到的方法对象
                args: 被拦截到的方法对象的参数
        	返回值:
        		和被代理对象方法有相同的返回值
		*/
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if("方法名".equals(method.getName())) {  //判断是哪个方法
            	// 增强方法的操作
                rtValue = method.invoke(被代理的对象, args);
                // 增强方法的操作
                return rtValue;
            }          
        }
    });

具体代码:
IProducer.interface

public interface IProducer {
    public void saleProduct(float money);
    public void afterService(float money);
}

Producer.java

public class Producer implements IProducer{
    public void saleProduct(float money){
        System.out.println("销售产品,并拿到钱:"+money);
    }

    public void afterService(float money){
        System.out.println("提供售后服务,并拿到钱:"+money);
    }
}

Client.java

public class Client {

    public static void main(String[] args) {
        final Producer producer = new Producer();
        IProducer proxyProducer = (IProducer)									 						  Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object returnValue = null;
                Float money = (Float)args[0];
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer,money*0.8f);
                }
                if ("afterService".equals(method.getName())){
                    returnValue = method.invoke(producer,money*0.2f);
                }
                return returnValue;
            }
        });
        proxyProducer.saleProduct(10000f);
        //proxyProducer.afterService(10000f);

    }
}

基于子类的动态代理:

基于子类的动态代理:
涉及的类:Enhancer
提供者:第三方 cglib 库
如何创建代理对象:
使用 Enhancer 类中的 create 方法
创建代理对象的要求:
被代理类不能是最终类
create 方法的参数:
Class : 它是用于被指定代理对象的字节码
callback : 用于提供增强的代码
它是让我们写如何代理。我们一般是写一个该接口的实现类,通常是匿名内部类,但不是必须的。此接口的实现类都 是谁用谁写。
我们一般写的都是该接口的子实现类:MethodInterCeptor

pom.xml

<dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>
</dependencies>

Producer.java

public class Producer {
    public void saleProduct(float money){
        System.out.println("销售产品,并拿到钱:"+money);
    }

    public void afterService(float money){
        System.out.println("提供售后服务,并拿到钱:"+money);
    }
}

Client.java

/**
   * 模拟一个消费者
   */
  public class Client {
      public static void main(String[] args) {
          final Producer producer = new Producer();
          Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
              /**
             * 执行被代理对象的任何方法都会经过该方法
             * @param proxy
             * @param method
             * @param args
             *    以上三个参数和基于接口的动态代理中invoke方法的参数是一样的
             * @param methodProxy :当前执行方法的代理对象
             * @return
             * @throws Throwable
             */
              public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                  // 提供增强的代码
                  Object returnValue = null;
                  // 1.获取方法执行的参数
                  Float money = (Float)args[0];
                  // 2.判断当前方法是不是销售
                  if ("saleProduct".equals(method.getName())) {
                      returnValue = method.invoke(producer,money * 0.8f);
                  }
                  return returnValue;
              }
          });
          cglibProducer.saleProduct(12000f);
      }
  }

2.使用动态代理解决第8.1小节代码冗余现象

我们使用动态代理对上述Service进行改造,创建BeanFactory类作为service层对象工厂,通过其getAccountService方法得到业务层对象.

BeanFactory.java

// 用于创建Service的代理对象的工厂
public class BeanFactory {

	private IAccountService accountService;		// 被增强的service对象
	private TransactionManager txManager;		// 事务控制工具类

	// 成员变量的set方法,以便Spring容器注入
	public void setTxManager(TransactionManager txManager) {
		this.txManager = txManager;
	}
	public final void setAccountService(IAccountService accountService) {
		this.accountService = accountService;
	}

	// 获取增强后的Service对象
	public IAccountService getAccountService() {
		return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
			accountService.getClass().getInterfaces(),
			new InvocationHandler() {
				// 增强方法
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					Object rtValue = null;
					try {
						//1.开启事务
						txManager.beginTransaction();
						//2.执行操作
						rtValue = method.invoke(accountService, args);
						//3.提交事务
						txManager.commit();
						//4.返回结果
						return rtValue;
					} catch (Exception e) {
						//5.回滚操作
						txManager.rollback();
						throw new RuntimeException(e);
					} finally {
						//6.释放连接
						txManager.release();
					}
				}
			});
	}
}

bean.xml中,添加如下配置:

<!--配置beanfactory-->
<bean id="beanFactory" class="com.factory.BeanFactory">
	<!-- 注入service -->
    <property name="accountService" ref="accountService"></property>
    <!-- 注入事务控制工具 -->
    <property name="txManager" ref="txManager"></property>
</bean>

<!--配置代理的service-->
    <bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>

在测试类Test中:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    @Qualifier("proxyAccountService")
    private IAccountService as;

    @Test
    public void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }

}

9.AOP( 面向切面编程 ) 的概念

什么是AOP?
在单体架构下的软件开发中,一个大型项目通常是依照功能拆分成各个模块。但是如日志、安全和事务管理此类重要 且繁琐的开发却没有必要参与到各个模块中,将这些功能与业务逻辑相关的模块分离就是面向切面编程所要解决的问题

AOP采取的是横向抽取机制,取代了传统纵向继承体系重复性代码。

那么何为软件的横向和纵向?
从纵向结构来看就是我们软件的各个模块,它所负责的是软件的核心业务(如购商品购买、添加购物车等);从横向 来看的话,软件的各个模块之间又有所关联,其中会包含一些公共模块(例如日志、权限等);这些公共模块可以存在 于各个核心业务中,而AOP的处理将两者分离,使开发人员可以专注于核心业务的开发,提高了开发效率。

AOP 的作用及优势
作用: 在程序运行期间,不修改源码对已有方法进行增强。
优势: 减少重复代码 提高开发效率 维护方便

AOP底层原理
使用动态代理实现
(1)基于JDK的代理
适用于有接口情况,使用动态代理创建接口实现类代理对象

​ (2)基于CGLIB动态代理
​ 适用于没有接口情况,使用动态代理创建类的子类代理对象

AOP相关术语:

  • Advice (通知/增强): 所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
  • Joinpoint (连接点): 所谓连接点是指那些被拦截到的点。在 Spring 中,这些点指的是方法,因为 Spring 只支持方法类型的连接点。
  • Pointcut (切入点): 我们对其进行增强的方法。
  • Target(目标对象): 被代理的目标对象。
  • Weaving (织入): 是指把增强应用到目标对象来创建新的代理对象的过程。 Spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
  • Proxy(代理): 一个类被 AOP 织入增强后,就产生一个结果代理类。
  • Aspect (切面): 是切入点和通知的结合。

10.使用XML配置AOP

要在pom.xml文件导入以下包:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>

使用XML配置AOP的步骤
bean.xml中配置AOP要经过以下几步:
1.在bean.xml中引入约束并将通知类注入Spring容器中

<?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 id="logger" class="cn.utils.Logger"></bean>
</beans>

2.使用<aop:config>标签声明AOP配置,所有关于AOP配置的代码都写在<aop:config>标签内

<aop:config>
	<!-- AOP配置的代码都写在此处 -->
</aop:config>

3.使用<aop:aspect>标签配置切面,其属性如下:
​ id :指定切面的id
​ ref :引用通知类的id

<aop:config>
	<aop:aspect id="logAdvice" ref="logger">
    	<!--配置通知的类型要写在此处-->
    </aop:aspect>
</aop:config>

4.使用<aop:pointcut>标签配置切入点表达式,指定对哪些方法进行增强,其属性如下:
​ id :指定切入点表达式的id
​ expression :指定切入点表达式

<aop:config>
	<aop:aspect id="logAdvice" ref="logger">
		<aop:pointcut expression="execution(* com.service.impl.*.*(..))" id="pt1">						</aop:pointcut>
	</aop:aspect>
</aop:config>

5.使用<aop:xxx>标签配置对应类型的通知方法
​ 1.其属性如下:
​ 1.method: 指定通知类中的增强方法名.
​ 2.ponitcut-ref: 指定切入点的表达式的id
​ 3.poinitcut: 指定切入点表达式
​ 其中pointcut-refpointref属性只能有其中一个
​ 2.具体的通知类型:
<aop:before>: 配置前置通知,指定的增强方法在切入点方法之前执行.
<aop:after-returning>: 配置后置通知,指定的增强方法在切入点方法正常执行之后执行.
<aop:after-throwing>: 配置异常通知,指定的增强方法在切入点方法产生异常后执行.
<aop:after>: 配置最终通知,无论切入点方法执行时是否发生异常,指定的增强方法都会最后执行.
<aop:around>: 配置环绕通知,可以在代码中手动控制增强代码的执行时机.环绕通知一般单独使用

<aop:config>
    <aop:aspect id="logAdvice" ref="logger">
        <!--指定切入点表达式-->
        <aop:pointcut expression="execution(* com.service.impl.*.*(..))" id="pt1"></aop:pointcut>
        <!--配置各种类型的通知-->
        <aop:before method="printLogBefore" pointcut-ref="pt1"></aop:before>
        <aop:after-returning method="printLogAfterReturning" pointcut-ref="pt1"></aop:after-returning>
        <aop:after-throwing method="printLogAfterThrowing" pointcut-ref="pt1"></aop:after-throwing>
        <aop:after method="printLogAfter" pointcut-ref="pt1"></aop:after>
		<!--环绕通知一般单独使用-->       
        <!-- <aop:around method="printLogAround" pointcut-ref="pt1"></aop:around> -->
    </aop:aspect>
</aop:config>

切入点表达式

切入点表达式的写法: execution( [修饰符] 返回值类型 包路径.类名.方法名(参数) )

切入点表达式的省略写法:
标准的表达式写法:

<aop:pointcut expression="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())" id="pt1"></aop:pointcut>

​ 访问修饰符可以省略:

<aop:pointcut expression="execution(void com.itheima.service.impl.AccountServiceImpl.saveAccount())" id="pt1"></aop:pointcut>

​ 返回值可以使用通配符,表示任意返回值:

<aop:pointcut expression="execution(* com.itheima.service.impl.AccountServiceImpl.saveAccount())" id="pt1"></aop:pointcut>

​ 包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*:

<aop:pointcut expression="execution(* *.*.*.*.AccountServiceImpl.saveAccount())" id="pt1"></aop:pointcut>

​ 包名可以使用…表示当前包及其子包:

<aop:pointcut expression="execution(* *..AccountServiceImpl.saveAccount())" id="pt1"></aop:pointcut>

​ 类名和方法名都可以使用*来实现通配:

<aop:pointcut expression="execution(* *..*.*())" id="pt1"></aop:pointcut>

​ 方法的参数列表:
​ 可以直接写数据类型:
​ 基本类型直接写名称 int
​ 引用类型写包名.类名的方式 java.lang.String
​ 可以使用通配符表示任意类型,但是必须有参数
​ 可以使用…表示有无参数均可,有参数可以是任意类型

​ 全通配写法:

<aop:pointcut expression="execution(* *..*.*(..))" id="pt1"></aop:pointcut>

实际开发中切入点表达式的通常写法:
切到业务层实现类下的所有方法

<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"></aop:pointcut>

**环绕通知 (一般单独使用) **

1.前置通知,后置通知,异常通知,最终通知的执行顺序
Spring是基于动态代理对方法进行增强的,前置通知,后置通知,异常通知,最终通知在增强方法中的执行时机如下:

// 增强方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
    Object rtValue = null;
    try {
        // 执行前置通知
        000000
        // 执行原方法
        rtValue = method.invoke(accountService, args); 
        
        // 执行后置通知
        ......
        return rtValue;
    } catch (Exception e) {
        // 执行异常通知
        ......
    } finally {
        // 执行最终通知
        ......
    }
}

2.环绕通知允许我们更自由地控制增强代码执行的时机:
Spring框架为我们提供一个接口ProceedingJoinPoint,它的实例对象可以作为环绕通知方法的参数,通过参数控制被增强 方法的执行时机.
ProceedingJoinPoint对象的getArgs()方法返回被拦截的参数
ProceedingJoinPoint对象的proceed()方法执行被拦截的方法

// 环绕通知方法,返回Object类型
public Object printLogAround(ProceedingJoinPoint pjp) {
    Object rtValue = null;
    try {
        Object[] args = pjp.getArgs();        
        printLogBefore();			// 执行前置通知
    	rtValue = pjp.proceed(args);// 执行被拦截方法
        printLogAfterReturn();		// 执行后置通知
    }catch(Throwable e) {
        printLogAfterThrowing();	// 执行异常通知
    }finally {
        printLogAfter();			// 执行最终通知
    }
    return rtValue;
}

11.使用注解配置配置AOP

1.半注解配置AOP

半注解配置AOP,需要在bean,xml中有下面语句:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描的包 -->
    <context:component-scan base-package="com"></context:component-scan>
	<!-- 下面语句开启对注解AOP的支持 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

Spring用于AOP的注解 :

1.用于声明切面的注解:

@Aspect: 声明当前类为通知类,该类定义了一个切面.相当于xml配置中的<aop:aspect>标签

@Component("logger")
@Aspect
public class Logger {
    ......
}

2.用于声明通知的注解 :

@Before: 声明该方法为前置通知.相当于xml配置中的aop:before标签
@AfterReturning: 声明该方法为后置通知.相当于xml配置中的aop:after-returning标签
@AfterThrowing: 声明该方法为异常通知.相当于xml配置中的aop:after-throwing标签
@After: 声明该方法为最终通知.相当于xml配置中的aop:after标签
@Around: 声明该方法为环绕通知.相当于xml配置中的aop:around标签
​ 上面声明通知注解的属性:
​ value :用于指定切入点表达式 或 切入点表达式的引用

@Component("logger")
@Aspect	//表示当前类是一个通知类
public class Logger {

    // 配置前置通知
	@Before("execution(* com.service.impl.*.*(..))")
    public void printLogBefore(){
        System.out.println("前置通知Logger类中的printLogBefore方法开始记录日志了。。。");
    }

    // 配置后置通知
    @AfterReturning("execution(* com.service.impl.*.*(..))")
    public void printLogAfterReturning(){
        System.out.println("后置通知Logger类中的printLogAfterReturning方法开始记录日志了。。。");
    }
    
    // 配置异常通知
	@AfterThrowing("execution(* com.service.impl.*.*(..))")
    public void printLogAfterThrowing(){
        System.out.println("异常通知Logger类中的printLogAfterThrowing方法开始记录日志了。。。");
    }

    // 配置最终通知
    @After("execution(* com.service.impl.*.*(..))")
    public void printLogAfter(){
        System.out.println("最终通知Logger类中的printLogAfter方法开始记录日志了。。。");
    }

    // 配置环绕通知  
    //@Around("execution(* com.service.impl.*.*(..))")
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();	
			printLogBefore();				// 执行前置通知
            rtValue = pjp.proceed(args);	// 执行切入点方法
			printLogAfterReturning();		// 执行后置通知
            return rtValue;
        }catch (Throwable t){
            printLogAfterThrowing();		// 执行异常通知
            throw new RuntimeException(t);
        }finally {
            printLogAfter();				// 执行最终通知
        }
    }
}

3.用于指定切入点表达式的注解:

@Pointcut: 指定切入点表达式,其属性如下:
value: 指定表达式的内容
@Pointcut注解没有id属性,通过调用被注解的方法获取切入点表达式.

@Component("logger")
@Aspect	//表示当前类是一个通知类
public class Logger {

    // 配置切入点表达式
    @Pointcut("execution(* com.service.impl.*.*(..))")
    private void pt1(){} 
    
    // 通过调用被注解的方法获取切入点表达式
	@Before("pt1()") //一定要加引号和括号
    public void printLogBefore(){
        System.out.println("前置通知Logger类中的printLogBefore方法开始记录日志了。。。");
    }

    // 通过调用被注解的方法获取切入点表达式
    @AfterReturning("pt1()")    //一定要加引号和括号
    public void printLogAfterReturning(){
        System.out.println("后置通知Logger类中的printLogAfterReturning方法开始记录日志了。。。");
    }
    
    // 通过调用被注解的方法获取切入点表达式
	@AfterThrowing("pt1()")    //一定要加引号和括号
    public void printLogAfterThrowing(){
        System.out.println("异常通知Logger类中的printLogAfterThrowing方法开始记录日志了。。。");
    }
}

2.纯注解配置AOP

在Spring配置类前添加**@EnableAspectJAutoProxy**注解,可以使用纯注解方式配置AOP

@Configuration
@ComponentScan(basePackages="com")
@EnableAspectJAutoProxy			// 允许AOP
public class SpringConfiguration {
    // 具体配置
    //...
}

3.使用注解配置AOP的bug

在使用注解配置AOP时,会出现一个bug. 四个通知的调用顺序依次是:前置通知,最终通知,后置通知. 这会导致一些资源在执行最终通知时提前被释放掉了,而执行后置通知时就会出错。(环绕通知除外,因为环绕通知是自己定义的代码)

12.JdbcTemplate

1.JdbcTemplate概述

JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似.

2.JdbcTemplate对象的创建

  1. 配置数据源: JdbcTemplate对象在执行sql语句时也需要一个数据源,这个数据源可以使用Spring的内置数据源DriverManagerDataSource.

  2. 创建JdbcTemplate对象:

    JdbcTemplate的构造方法传入数据源创建对象。

    在bean.xml中配置如下:

  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
          <property name="dataSource" ref="dataSource"></property>
      </bean>
      
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
          <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
          <property name="username" value="root"></property>
          <property name="password" value="123456"></property>
      </bean>
  </beans>

在测试类使用实例:

public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class); //第二个参数是将返回值强制类型转换
        //执行操作
        jt.execute("insert into account(name,money) values('qqq',2222)");
    }

3.JdbcTemplate的增删改查操作

使用JdbcTemplate实现增删改

  1. 增加操作
public static void main(String[] args) {
    //1.获取Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    //2.根据id获取JdbcTemplate对象
    JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
    //3.执行增加操作
    jt.update("insert into account(name,money)values(?,?)","名字",5000);
}
  1. 删除操作
   public static void main(String[] args) {
       //1.获取Spring容器
       ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
       //2.根据id获取JdbcTemplate对象
       JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
       //3.执行删除操作
       jt.update("delete from account where id = ?",6);
   }
  1. 更新操作
public static void main(String[] args) {
	//1.获取Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    //2.根据id获取JdbcTemplate对象
    JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
    //3.执行更新操作
	jt.update("update account set money = money-? where id = ?",300,6);
}

使用JdbcTemplate实现查询

JdbcTemplate的查询操作使用其query()方法,其参数如下:
String sql: SQL语句
RowMapper rowMapper: 指定如何将查询结果ResultSet对象转换为T对象.
@Nullable Object… args: SQL语句的参数

其中RowMapper类类似于DBUtilsResultSetHandler类,可以自己写一个实现类,但常用Spring框架内置的实现类BeanPropertyRowMapper<T>(T.class)

1.查询所有:

 public static void main(String[] args) {
     ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
     JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
     List<Account> accounts;
     accounts = jt.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
     for(Account account:accounts){
         System.out.println(account);
    }
}

2.查询符合条件的记录:

public static void main(String[] args) {
     ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
     JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
  	List<Account> accounts = jt.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class),1000f);
     for(Account account:accounts)
          System.out.println(account);

3.查询一条记录:

public static void main(String[] args) {
     ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
     JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
   	 List<Account> accounts = jt.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class),1);
     System.out.println(accounts.isEmpty() ?"没有内容": accounts.get(0));
}

4.聚合查询:

JdbcTemplate中执行聚合查询的方法为queryForObject()方法,其参数如下:

  • String sql: SQL语句
  • Class<T> requiredType: 返回类型的字节码
  • @Nullable Object... args: SQL语句的参数
public static void main(String[] args) {
    //1.获取Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    //2.根据id获取JdbcTemplate对象
    JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
    //3.聚合查询
    Integer total = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 500);
    System.out.println(total);
}

4.在DAO层使用JdbcTemplate

在DAO层直接使用JdbcTemplate

在DAO层使用JdbcTemplate,需要给DAO注入JdbcTemplate对象.

public class AccountDaoImpl implements IAccountDao {
    
    private JdbcTemplate jdbcTemplate;	// JdbcTemplate对象

    // JdbcTemplate对象的set方法
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // DAO层方法
    @Override
    public Account findAccountById(Integer id) {
        // 实现...
    }

    // DAO层方法
    @Override
    public Account findAccountByName(String name) {
        // 实现...
    }

    // 其它DAO层方法...
}

在bean,xml中添加以下:

<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

DAO层对象继承JdbcDaoSupport类

在实际项目中,我们会创建许多DAO对象,若每个DAO对象都注入一个JdbcTemplate对象,会造成代码冗余.

实际的项目中我们可以让DAO对象继承Spring内置的JdbcDaoSupport类.在JdbcDaoSupport类中定义了JdbcTemplate和DataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSource的set方法中会注入JdbcTemplate对象.
DAO的实现类中调用父类的getJdbcTemplate()方法获得JdbcTemplate()对象.

JdbcDaoSupport类的源代码如下:

public abstract class JdbcDaoSupport extends DaoSupport {
    
    @Nullable
    private JdbcTemplate jdbcTemplate;	// 定义JdbcTemplate成员变量

    public JdbcDaoSupport() {
    }

    // DataSource的set方法,注入DataSource时调用createJdbcTemplate方法注入JdbcTemplate
    public final void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = this.createJdbcTemplate(dataSource);
            this.initTemplateConfig();
        }
    }

    // 创建JdbcTemplate,用来被setDataSource()调用注入JdbcTemplate
    protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    // JdbcTemplate的get方法,子类通过该方法获得JdbcTemplate对象
    @Nullable
    public final JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    @Nullable
    public final DataSource getDataSource() {
        return this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null;
    }

    public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.initTemplateConfig();
    }

    // ...
}


bean.xml中,我们只要为DAO对象注入DataSource对象即可,让JdbcDaoSupport自动调用JdbcTemplate的set方法注入JdbcTemplate:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/数据库名"></property>
        <property name="username" value="用户名"></property>
        <property name="password" value="密码"></property>
    </bean>

    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
        <!--不用我们手动配置JdbcTemplate成员了-->
        <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

在DAO类接口中,只需定义并实现DAO层方法即可.

public interface IAccountDao {
	
    // 根据id查询账户信息
	Account findAccountById(Integer id);

	// 根据名称查询账户信息
	Account findAccountByName(String name);

	// 更新账户信息
	void updateAccount(Account account);
}

在实现DAO接口时,我们通过super.getJdbcTemplate()方法获得JdbcTemplate对象:

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    
    @Override
    public Account findAccountById(Integer id) {
		//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        List<Account> list = getJdbcTemplate().query("select * from account whereid = ? ", new AccountRowMapper(), id);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        //调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        List<Account> accounts = getJdbcTemplate().query("select * from account wherename = ? ", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {
            return null;
        } else if (accounts.size() > 1) {
            throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
		//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
    }
}

但是这种配置方法存在一个问题: 因为我们不能修改JdbcDaoSupport类的源代码,DAO层的配置就只能基于xml配置,而不再可以基于注解配置了.

13.Spring事务控制

1.JavaEE 体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方

2.Spring 框架为我们提供了一组事务控制的接口,这组接口在spring-tx-5.0.2.RELEASE.jar中

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

3.Spring 的事务控制都是基于AOP的,它既可以使用配置的方式实现,也可以使用编程的方式实现.推荐使用配置方式实现.

1.数据库事务的基础知识

1.事务的四大特性:ACID

​ 1.原子性(Atomicity): 事务包含的所有操作要么全部成功,要么全部失败回滚;成功必须要完全应用到数据库,失败则不能对数据库产生影响.
​ 2.一致性(Consistency):事务执行前和执行后必须处于一致性状态.例如:转账事务执行前后,两账户余额的总和不变.
​ 3.隔离性(Isolation): 多个并发的事务之间要相互隔离.
​ 4.持久性(Durability): 事务一旦提交,对数据库的改变是永久性的.

其他知识和细节:
详细请见网址:https://blog.csdn.net/ncepu_Chen/article/details/94857481

2.Spring中事务控制的API

1.PlatformTransactionManager接口是Spring提供的事务管理器,它提供了操作事务的方法如下:

​ 1.TransactionStatus getTransaction(TransactionDefinition definition): 获得事务状态信息
​ 2.void commit(TransactionStatus status): 提交事务
​ 3.void rollback(TransactionStatus status): 回滚事务
​ 在实际开发中我们使用其实现类:

​ 1.org.springframework.jdbc.datasource.DataSourceTransactionManager使用SpringJDBC或iBatis进行持久化数据时使用
​ 2.org.springframework.orm.hibernate5.HibernateTransactionManager使用Hibernate版本进行持久化数据时使用

2.TransactionDefinition: 事务定义信息对象,提供查询事务定义的方法如下:

​ 1.String getName(): 获取事务对象名称

​ 2.int getIsolationLevel(): 获取事务隔离级别,设置两个事务之间的数据可见性

事务的隔离级别由弱到强,依次有如下五种:(可以参考文章事务的四种隔离级别,数据库事务4种隔离级别及7种传播行为)
​ 1.ISOLATION_DEFAULT: Spring事务管理的的默认级别,使用数据库默认的事务隔离级别.
​ 2.ISOLATION_READ_UNCOMMITTED: 读未提交.
​ 3.ISOLATION_READ_COMMITTED: 读已提交.
​ 4.ISOLATION_REPEATABLE_READ: 可重复读.
​ 5.ISOLATION_SERIALIZABLE: 串行化.

​ 3.getPropagationBehavior(): 获取事务传播行为,设置新事务是否事务以及是否使用当前事务.

​ 我们通常使用的是前两种:REQUIREDSUPPORTS.事务传播行为如下:

​ 1.REQUIRED: Spring默认事务传播行为. 若当前没有事务,就新建一个事务;若当前已经存在一个事务中,加入到这个事务中.增删改查操作均可用
​ 2.SUPPORTS: 若当前没有事务,就不使用事务;若当前已经存在一个事务中,加入到这个事务中.查询操作可用
​ 3.MANDATORY: 使用当前的事务,若当前没有事务,就抛出异常
​ 4.REQUERS_NEW: 新建事务,若当前在事务中,把当前事务挂起
​ 5.NOT_SUPPORTED: 以非事务方式执行操作,若当前存在事务,就把当前事务挂起
​ 6.NEVER:以非事务方式运行,若当前存在事务,抛出异常
​ 7.NESTED:若当前存在事务,则在嵌套事务内执行;若当前没有事务,则执行REQUIRED类似的操作

​ 4.int getTimeout(): 获取事务超时时间. Spring默认设置事务的超时时间为-1,表示永不超时.

​ 5.boolean isReadOnly(): 获取事务是否只读. Spring默认设置为false,建议查询操作中设置为true

3.TransactionStatus: 事务状态信息对象,提供操作事务状态的方法如下:

​ 1.void flush(): 刷新事务
​ 2.boolean hasSavepoint(): 查询是否存在存储点
​ 3.boolean isCompleted(): 查询事务是否完成
​ 4.boolean isNewTransaction(): 查询是否是新事务
​ 5.boolean isRollbackOnly(): 查询事务是否回滚
​ 6.void setRollbackOnly(): 设置事务回滚

3.使用Spring进行事务控制

1.项目准备

pom.xml:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

创建bean.xml并导入约束

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

java实体类如下:

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {return id; }    
    public void setId(Integer id) {this.id = id; }    
    public String getName() {return name; }  
    public void setName(String name) {this.name = name; }   
    public Float getMoney() {return money; }    
    public void setMoney(Float money) {this.money = money; }

    @Override
    public String toString() {return "Account{id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } 

编写Dao层接口和实现类:

Dao层接口:

// 持久层接口
public interface IAccountDao {
    
    // 根据Id查询账户
    Account findAccountById(Integer accountId);

    // 根据名称查询账户
    Account findAccountByName(String accountName);

    // 更新账户
    void updateAccount(Account account);
}

Dao层实现类:

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    public Account findAccountById(Integer accountId) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if (accounts.isEmpty()){
            return null;
        }
        if (accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set name =?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }

编写Service层接口和实现类:

Service层接口

//  业务层接口
public interface IAccountService {

    // 根据id查询账户信息
    Account findAccountById(Integer accountId);

    // 转账
    void transfer(String sourceName,String targetName,Float money);
}

Service层实现类:

// 业务层实现类,事务控制应在此层
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("start transfer");
        // 1.根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        // 2.根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        // 3.转出账户减钱
        source.setMoney(source.getMoney() - money);
        // 4.转入账户加钱
        target.setMoney(target.getMoney() + money);
        // 5.更新转出账户
        accountDao.updateAccount(source);

        int i = 1 / 0;

        // 6.更新转入账户
        accountDao.updateAccount(target);
    }
}

bean.xml中配置数据源等


<bean id="accountService" class="com.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--配置 数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
</bean>    

2.使用xml配置事务控制

Spring的配置式事务控制本质上是基于AOP的,因此下面我们在bean.xml中配置事务管理器PlatformTransactionManager对象并将其与AOP配置建立联系.

1.配置事务管理器并注入数据源

<!--向Spring容器中注入一个事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource" />
</bean>

2.配置事务通知并在通知中配置其属性

​ 使用**<tx:advice>标签声明事务配置,其属性如下:
​ 1.id: 事务配置的id
​ 2.transaction-manager: 该配置对应的事务管理器
​ 在
<tx:advice>标签内包含<tx:attributes>**标签表示配置事务属性

​ 在**<tx:attributes>标签内包含<tx:method>标签,为切面上的方法配置事务属性,<tx:method>*标签的属性如下:
​ 1.name: 拦截到的方法,可以使用通配符

​ 2.isolation: 事务的隔离级别,Spring默认使用数据库的事务隔离级别
​ 3.propagation: 事务的传播行为,默认为REQUIRED.增删改方法应该用REQUIRED,查询方法可以使用SUPPORTS
​ 4.read-only: 事务是否为只读事务,默认为false.增删改方法应该用false,查询方法可以使用true
​ 5.timeout: 指定超时时间,默认值为-1,表示永不超时
​ 6.rollback-for: 指定一个异常,当发生该异常时,事务回滚;发生其他异常时,事务不回滚.无默认值,表示发生任何异常都回滚
​ 7.no-rollback-for: 指定一个异常,当发生该异常时,事务不回滚;发生其他异常时,事务回滚.无默认值,表示发生任何异常都回滚

<!-- 配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--匹配所有方法-->
        <tx:method name="*" propagation="REQUIRED" read-only="false" />      
        <!--匹配所有查询方法-->
        <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
       <!--第二个<tx:method>匹配得更精确,所以对所有查询方法,匹配第二个事务管理配置;对其他方法,匹配第一个事务管理配置-->
    </tx:attributes>
</tx:advice>

3.配置AOP并为事务管理器事务管理器指定切入点

<!--配置AOP-->
<aop:config>
    <!-- 配置切入点表达式-->
    <aop:pointcut id="pt1" expression="execution(* cn,maoritian.service.impl.*.*(..))"></aop:pointcut>
    <!--为事务通知指定切入点表达式-->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>

3.使用半注解配置事务控制

需在项目准备的每个实现类前加上注解IOC(例:@Service()等)
因为JdbcDaoSupport不能修改源码,不能使用注解,所以要在Dao实现类删除且修改

Dao实现类:

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if (accounts.isEmpty()){
            return null;
        }
        if (accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name =?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

1.bean.xml里的实现:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!-- 配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

    <!-- spring中基于注解 的声明式事务控制配置步骤
        1、配置事务管理器
        2、开启spring对注解事务的支持
        3、在需要事务支持的地方使用@Transactional注解  -->
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>

2.在需要事务支持的地方使用@Transactional注解,其参数与<tx:method>的属性一致.
​ 该注解可以加在接口,类或方法上

  • 对接口加上@Transactional注解,表示对该接口的所有实现类进行事务控制

  • 对类加上@Transactional注解,表示对类中的所有方法进行事务控制

  • 对具体某一方法加以@Transactional注解,表示对具体方法进行事务控制

    三个位置上的注解优先级依次升高

    // 业务层实现类,事务控制应在此层
    @Service("accountService")
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)    // 读写型事务配置
    public class AccountServiceImpl implements IAccountService {
    
        @Autowired
        private IAccountDao accountDao;
    
        @Override
        @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
        // 只读型事务配置,会覆盖上面对类的读写型事务配置 
        public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
        }
     
        @Override
        public void transfer(String sourceName, String targetName, Float money) {
            // 转账操作的实现...
        }
    }
    

4.使用纯注解式事务配置

不使用xml配置事务,就要在com.config包下新建一个事务管理配置类**TransactionConfig,对其加上@EnableTransactionManagement**注解以开启事务控制.

事务控制配置类TransactionConfig类:

@Configuration                  
@EnableTransactionManagement    // 开启事务控制
public class TransactionConfig {
    // 创建事务管理器对象
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

JDBC配置类JdbcConfig类:

@Configuration                                  
@PropertySource("classpath:jdbcConfig.properties")  
public class JdbcConfig {

    @Value("${jdbc.driver}")    
    private String driver;

    @Value("${jdbc.url}")   
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")  
    private String password;

    // 创建JdbcTemplate对象
    @Bean(name="jdbcTemplate")
    @Scope("prototype")   //指定Bean是多例
    public JdbcTemplate createJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    
    // 创建数据源对象
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

Spring主配置类SpringConfig如下:

@Configuration
@ComponentScan("com")
@Import({JdbcConfig.class, TransactionConfig.class})
public class SpringConfig {
}
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
```

2.在需要事务支持的地方使用@Transactional注解,其参数与<tx:method>的属性一致.
​ 该注解可以加在接口,类或方法上

  • 对接口加上@Transactional注解,表示对该接口的所有实现类进行事务控制

  • 对类加上@Transactional注解,表示对类中的所有方法进行事务控制

  • 对具体某一方法加以@Transactional注解,表示对具体方法进行事务控制

    三个位置上的注解优先级依次升高

    // 业务层实现类,事务控制应在此层
    @Service("accountService")
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)    // 读写型事务配置
    public class AccountServiceImpl implements IAccountService {
    
        @Autowired
        private IAccountDao accountDao;
    
        @Override
        @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
        // 只读型事务配置,会覆盖上面对类的读写型事务配置 
        public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
        }
     
        @Override
        public void transfer(String sourceName, String targetName, Float money) {
            // 转账操作的实现...
        }
    }
    

4.使用纯注解式事务配置

不使用xml配置事务,就要在com.config包下新建一个事务管理配置类**TransactionConfig,对其加上@EnableTransactionManagement**注解以开启事务控制.

事务控制配置类TransactionConfig类:

@Configuration                  
@EnableTransactionManagement    // 开启事务控制
public class TransactionConfig {
    // 创建事务管理器对象
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

JDBC配置类JdbcConfig类:

@Configuration                                  
@PropertySource("classpath:jdbcConfig.properties")  
public class JdbcConfig {

    @Value("${jdbc.driver}")    
    private String driver;

    @Value("${jdbc.url}")   
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")  
    private String password;

    // 创建JdbcTemplate对象
    @Bean(name="jdbcTemplate")
    @Scope("prototype")   //指定Bean是多例
    public JdbcTemplate createJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    
    // 创建数据源对象
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

Spring主配置类SpringConfig如下:

@Configuration
@ComponentScan("com")
@Import({JdbcConfig.class, TransactionConfig.class})
public class SpringConfig {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值