1 程序的耦合

  1. /**
  2. * 程序的耦合:
  3. * 耦合:程序间的依赖关系
  4. * 包括:类之间的依赖
  5. * 方法之间的依赖
  6. * 解耦:降低程序间的依赖关系
  7. * 实际开发中,应该做到:编译器不依赖,运行时才依赖
  8. * 解决的思路:
  9. * 第一步:使用反射来创建对象,而避免使用new关键字
  10. * 第二步:通过读取配置文件,获取要创建的对象全限定类名
  11. */

2 什么是Bean???


  • Bean:在计算机英语中,由可重用组件的含义
  • JavaBean:用java语言编写的,可重用组件, javaBean >= 实体类

Bean的创建有三种方式

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!--把对象的创建交给是spring来管理-->
  7. <!--spingbean的管理细节
  8. 1. 创建bean的三种方式
  9. 2. bean对象的作用范围
  10. 3. bean对象的生命周期
  11. -->
  12. <!--创建bean的三种方式-->
  13. <!--第一种方式:使用默认构造函数创建。
  14. spring的配置文件中,使用bean标签,配以idclass属性之后,且没有其他属性和标签时。
  15. 采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建-->
  16. <!--<bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl"></bean>-->
  17. <!--第二种方式:使用普通工厂中的方法创建对象,或者使用某个类中的方法创建对象,并存入spring容器-->
  18. <!--<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
  19. <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>-->
  20. <!--第三种方式:使用工厂中的静态方法创建对象,使用某个类中的静态方法创建对象,并存入spring容器-->
  21. <!--<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>-->
  22. <!--bean的作用范围调整
  23. bean标签的scope属性:用于指定bean的作用范围
  24. 取值:
  25. singleton:单例(默认值)
  26. prototype:多例的
  27. request:作用于web应用的请求范围
  28. session:作用于web应用的会话范围
  29. global-session:作用域集群环境的会话范围(全局会话范围),当不是集群环境时,他就是session
  30. -->
  31. <!--<bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="singleton"></bean>-->
  32. <!--bean对象的生命周期
  33. 单例对象:
  34. 出生:当容器创建对象时出生
  35. 活着:只要容器还在,对象一直活着
  36. 死亡:容器销毁,对象消亡
  37. 总结:单例对象的生命周期和容器相同
  38. 多例对象:
  39. 出生:当我们使用对象时,spring框架为我们创建
  40. 活着:对象只要在使用过程中就一直活着
  41. 死亡:当对象长时间不用,且没有别的对象引用时,由Java的垃圾回收机制处理
  42. -->
  43. <bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="singleton"
  44. init-method="init" destroy-method="destory"></bean>
  45. </beans>

3 工厂类的产生

  1. package com.itheima.factory;
  2. import jdk.internal.util.xml.impl.Input;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Enumeration;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.Properties;
  9. /**
  10. * 一个创建Bean对象的工厂
  11. *
  12. * Bean:在计算机英语中,由可重用组件的含义
  13. * JavaBean:用java语言编写的,可重用组件
  14. * javaBean >= 实体类
  15. * 它就是创建我们的service和dao对象的
  16. * 第一个:需要一个配置文件来配置我们的service和dao
  17. * 配置的内容:唯一标志=全限定类名(key=value)
  18. * 第二个:通过读取配置文件中的配置内容,反射创建对象
  19. * 配置文件可以是xml也可以是properties
  20. */
  21. public class BeanFactory {
  22. //定义一个Properties对象
  23. private static Properties props;
  24. //定义一个Map,用于存放我们要创建的对象,我们把它称之为容器
  25. private static Map<String, Object> beans;
  26. //使用静态代码块为Properties对象赋值
  27. static {
  28. //实例化
  29. try {
  30. props = new Properties();
  31. //获取propertoes文件的流对象
  32. InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
  33. props.load(in);
  34. //实例化容器
  35. beans = new HashMap<String, Object>();
  36. //取出配置文件中所有的key
  37. Enumeration keys = props.keys();
  38. //遍历枚举
  39. while (keys.hasMoreElements()) {
  40. //取出每个key
  41. String key = keys.nextElement().toString();
  42. //根据key获取value
  43. String beanPath = props.getProperty(key);
  44. //反射创建对象
  45. Object value = Class.forName(beanPath).newInstance();
  46. //把key和value存入容器中
  47. beans.put(key, value);
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. /**
  54. * 根据Bean的名称获取Bean对象
  55. * @param beanName
  56. * @return
  57. */
  58. /*public static Object getBean(String beanName) {
  59. Object bean = null;
  60. try {
  61. String beanPath = props.getProperty(beanName);
  62. //反射的方式
  63. bean = Class.forName(beanPath).newInstance(); //每次都会调用默认构造函数创建对象
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. return bean;
  68. }*/
  69. public static Object getBean(String beanName) {
  70. return beans.get(beanName);
  71. }
  72. }

4 ApplicationContext和BeanFactory的区别

  • 前者是后者的子接口,BeanFactory是Spring容器中的顶层接口
  • 创建对象的时间不同
    • ApplicationContext:只要一读取配置文件,默认情况下就会创建对象
    • BeanFactory:什么时候使用什么时候创建对象
  1. * ApplicationContext的三个常用实现类:
  2. * ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下, 不在的活加载不了
  3. * FileSystemXmlApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)
  4. * AnnotationConfigApplicationContext:用于读取注解创建容器的
  5. *
  6. * 核心容器的两个接口引发的问题:
  7. * ApplicationContext 单例对象适用 采用此接口
  8. * 他在构建核心容器时,创建对象采取的策略是采用立即加载的方式,也就是说,只要一读取完配置文 件马上就创建配置文件中的配置对象。
  9. * BeanFatory: 多例对象适用
  10. * 他在构建核心容器时,创建对象采取的策略是采用延迟加载的方式,也就是说,什么时候根据id获取 了对象,什么时候才是真正的创建对象
  11. public static void main(String[] args) {
  12. //1. 获取核心容器对象, 单例在此处便实例化类对象了, prototype多例则在下方的getBean时才会实例化类对象, Object value = Class.forName(beanPath).newInstance();
  13. // ApplicationContext和BeanFactory是有区别的: 前者是后者的子接口
  14. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  15. // ApplicationContext ac = new FileSystemXmlApplicationContext("D:\\Learning_Material\\JAVA\\Black_house\\day01_03Spring\\src\\main\\resources\\bean.xml");
  16. //2. 根据id获取bean对象, 多态, 强转
  17. AccountService as1 = (AccountService) ac.getBean("accountService");
  18. AccountService as2 = (AccountService) ac.getBean("accountService");
  19. AccountDao adao = ac.getBean("accountDao", AccountDao.class);
  20. System.out.println(as1);
  21. System.out.println(as2);
  22. System.out.println(adao);
  23. // as.saveAccount();
  24. }
  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!--把对象的创建交给是spring来管理-->
  6. <bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="prototype"></bean>
  7. <bean id="accountDao" class="com.itheima.dao.Impl.AccountDaoImpl"></bean>
  8. </beans>

可以看出,accountService是一个多例的Bean对象
单例、多例的区别:SpringIOC容器中的bean默认都是单例的,指定多例需要使用scope="prototype"

  • 单例:在SpringIOC容器中只会实例化一个bean对象,后续的请求都公用这个请求
    • 优点:减少新生成实例的消耗、减少jvm垃圾回收的次数、可以快速的获取到bean
    • 缺点:在多并发的场景下,线程不安全(可使用线程同步机制、或者使用ThreadLocal)
  • 多例:每次调用都会创建一个新的bean对象,对象不会共享

4.1 BeanFactory和FactoryBean的区别与联系

  1. 两者都是接口;
  2. BeanFactory主要是用来创建Bean和获得Bean的;
  3. FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象;
  4. 通过BeanFactory和beanName获取bean时,如果beanName不加&则获取到对应bean的实例;如果beanName加上&,则获取到FactoryBean本身的实例
  5. FactoryBean 通常是用来创建比较复杂的bean(如创建mybatis的SqlSessionFactory很复杂),一般的bean 直接用xml配置即可,但如果创建一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean。

5 依赖注入

三种方式

构造函数注入

  1. <!--构造函数注入:
  2. 使用的标签:constructor-arg
  3. 标签出现的位置:bean标签的内部
  4. 标签中的属性:
  5. type:用于指定要注入的数据数据类型,改数据类型也是构造函数中某个或某些参数的类型
  6. index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置从0开始
  7. name: 用于指定给构造函数中指定名称的参数赋值
  8. value: 用于提供基本类型和String类型的数据
  9. ref:用于指定其他的bean类型数据,它指的就是在是springIOC核心容器中出现过的bean对象
  10. 优势:
  11. 在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功
  12. 弊端:
  13. 改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
  14. -->
  15. <bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" >
  16. <constructor-arg name="name" value="test"></constructor-arg>
  17. <constructor-arg name="age" value="18"></constructor-arg>
  18. <constructor-arg name="birthday" ref="now"></constructor-arg>
  19. </bean>
  20. <!--配置一个日期对象-->
  21. <bean id="now" class="java.util.Date"></bean>

Set方法注入(常用)

  1. <!--set方法注入
  2. 涉及的标签:property
  3. 出现的位置:bean标签的内部
  4. 标签的属性:
  5. name: 用于指定给构造函数中指定名称的参数赋值,即pojo类成员变量set方法名后面的字符串(大写变小写)
  6. value: 用于提供基本类型和String类型的数据
  7. ref:用于指定其他的bean类型数据,它指的就是在是springIOC核心容器中出现过的bean对象
  8. 优势:
  9. 创建对象没有明确限制,可以直接使用默认构造函数
  10. 弊端:
  11. 如果有某个成员必须有值,则获取对象set方法有可能没法执行
  12. -->
  13. <bean id="accountService2" class="com.itheima.service.Impl.AccountServiceImpl2">
  14. <property name="name" value="TEST"></property>
  15. <property name="age" value="13"></property>
  16. <property name="birthday" ref="now"></property>
  17. </bean>

使用注解注入

  1. <!--复杂类型的注入/集合类型的注入
  2. 用于给list结构集合注入的标签:
  3. list array set
  4. 用于给Map结构集合注入的标签:
  5. map props
  6. 结构相同,标签可以互换
  7. -->
  8. <bean id="accountService3" class="com.itheima.service.Impl.AccountServiceImpl3">
  9. <property name="myStrs">
  10. <array>
  11. <value>AAA</value>
  12. <value>BBB</value>
  13. <value>CCC</value>
  14. </array>
  15. </property>
  16. <property name="myList">
  17. <list>
  18. <value>AAA</value>
  19. <value>BBB</value>
  20. <value>CCC</value>
  21. </list>
  22. </property>
  23. <property name="mySet">
  24. <set>
  25. <value>AAA</value>
  26. <value>BBB</value>
  27. <value>CCC</value>
  28. </set>
  29. </property>
  30. <property name="myMap">
  31. <map>
  32. <entry key="testA" value="aaa"></entry>
  33. <entry key="testB">
  34. <value>BBB</value>
  35. </entry>
  36. </map>
  37. </property>
  38. <property name="myProps">
  39. <props>
  40. <prop key="testC">ccc</prop>
  41. <prop key="testD">ddd</prop>
  42. </props>
  43. </property>
  44. </bean>

6 注解详解

  1. package com.itheima.service.Impl;
  2. import com.itheima.dao.AccountDao;
  3. import com.itheima.dao.Impl.AccountDaoImpl;
  4. import com.itheima.domain.Account;
  5. import com.itheima.service.AccountService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Qualifier;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.stereotype.Service;
  10. import javax.annotation.Resource;
  11. import java.util.List;
  12. /**
  13. * 业务层实现类
  14. * 曾经xml的配置
  15. * <bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl"
  16. * scope="" init-method="" destory0method="">
  17. * <property name="" value="" / ref=""></property>
  18. * </bean>
  19. *
  20. * 用于创建对象的
  21. * 他们的作用就和XMl配置文件中编写一个<bean>标签实现的功能是一样的
  22. * @Component:
  23. * 作用:用于把当前类对象,存入spring容器中
  24. * 属性:
  25. * value:用于指定bean的id。当我们不写时,它的默认值时当前类名,且首字母改小写
  26. * Controller:一般用在表现层
  27. * Service:一般用在业务层
  28. * Respository:一般用在持久层
  29. * 以上三个注解他们的作用和属性于Component是一摸一样。
  30. * 它们三个是spring框架为我们提供明确的三层使用的注解,使我们三层对象更加清晰
  31. *
  32. * 用于注入数据的
  33. * 他们的作用就和在XMl配置文件中的bean标签中写一个<property>标签的作用是一样的
  34. * Autowired:
  35. * 作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配(不区分大小写??),就可以注入成功
  36. * 如果IOC容器中,没有任何bean类型和要注入的变量类型匹配,则报错
  37. * 出现位置:
  38. * 可以是变量上,也可以是方法上
  39. * 细节:
  40. * 在使用注解注入时,set方法就不是必须的了
  41. * Qualifier:
  42. * 作用:在按照类中注入的基础之上,再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以
  43. * 属性:
  44. * value:用于指定注入bean的id
  45. * Resource:
  46. * 作用:直接按照bean的id注入,它可以独立使用
  47. * 属性:
  48. * name:用于指定bean的id
  49. * 以上三个注解都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
  50. * 另外,集合类型的注入只能通过XML来实现
  51. *
  52. * Value注解:
  53. * 作用:用于注入基本类型和String类型的数据
  54. * 属性:
  55. * value:用于指定数据的值,它可以使用spring中的SpEL(也即是Spring的EL表达式)
  56. * SpEL的写法:${表达式}
  57. *
  58. * 用于改变作用范围的
  59. * 他们的作用就和在bean标签中使用的scope实行实现的功能是一样的
  60. * Scope
  61. * 作用:用于指定bean的作用范围
  62. * 属性:
  63. * value:指定范围的取值,常用取值:singleton(单例) prototype(多例)
  64. * 和生命周期相关的
  65. * 他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的
  66. * PreDestroy
  67. * 作用:用于指定销毁方法
  68. * PostConstruct
  69. * 作用:用于指定初始化方法
  70. */
  71. @Service(value = "accountService") // 即指定对应bean的id为accountService
  72. public class AccountServiceImpl implements AccountService {
  73. // 当以下的注解被注释掉后,默认使用的是相对应的配置文件
  74. // @Autowired
  75. // @Qualifier("accountDao1")
  76. private AccountDao accountDao;
  77. public void saveAccount() {
  78. accountDao.saveAccount();
  79. }
  80. public List<Account> findAllAccount() {
  81. return null;
  82. }
  83. public void setAccountDao(AccountDaoImpl accountDao) {
  84. }
  85. }

6.1 用于创建对象

相当于:<bean id = "" class= "">

用于创建对象:他们的作用就和XMl配置文件中编写一个标签实现的功能是一样的

@Component:

  • 作用:用于把当前类对象存入Spring容器中
  • 属性:value,用于指定bean的id,当我们不写时,他的默认值是当前的类名
  • 以下的三个注解都属于Component

@Controller: 表现层

@Service: 业务层

@Respository: 持久层

都是bean的注解形式

6.2 用于注入数据

相当于:<property name="" ref=""> <property name="" value="">

@Autowired

作用:
自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个 类型匹配 时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错。

@Value

作用:
注入基本数据类型和 String 类型数据的
属性:
value:用于指定值

@Qualifier

作用:
在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowired 一起使用;但是给方法参数注入时,可以独立使用。
属性:
value:指定 bean 的 id。

@Resource

作用:
直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
属性:
name:指定 bean 的 id。

6.3 用于改变作用范围

相当于:<bean id="" class="" scope="">

@Scope

作用:
指定 bean 的作用范围。
属性:
value:指定范围的值。 取值:singleton prototype request session globalsession

6.4 和生命周期相关

相当于:<bean id="" class="" init-method="" destory-method="">

@PostConstruct

作用:
用于指定初始化方法。

@PreDestroy

作用:
用于指定销毁方法。

6.5 关于Spring注解和XML的选择问题

image.png

7 配置类

  1. package config;
  2. import com.mchange.v2.c3p0.ComboPooledDataSource;
  3. import org.apache.commons.dbutils.QueryRunner;
  4. import org.springframework.context.annotation.*;
  5. import org.springframework.stereotype.Component;
  6. import javax.sql.DataSource;
  7. import java.beans.PropertyVetoException;
  8. /**
  9. * 该类是一个配置类,他的作用是和bean.xml是一样的
  10. * spring中的新注解
  11. * Configuration
  12. * 作用:指定当前类是一个配置类,来代替原先的XML配置文件
  13. * 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
  14. * ComponentScan:
  15. * 作用:用于通过注解指定spring在创建容器时要扫描的包
  16. * 属性:
  17. * value:它和basePackages的作用时一样的。都是用于只当创建容器时要扫描的包
  18. * 我们使用此注解就等同于在xml中配置了:<context:component-scan base-package="com.itheima"></context:component-scan>
  19. * Bean注解:
  20. * 作用:用于把当前方法的返回值(对象)作为bean对象存入spring的ioc容器中
  21. * 属性:
  22. * name:用于指定bean的id。当不写时,默认值是当前方法的名称
  23. * 细节:
  24. * 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
  25. 该注解只能写在方法上
  26. 和@Component的区别,@Bean作用在方法对象上,后者作用在类对象上
  27. * Import:
  28. * 作用:用于导入其他的配置类
  29. * 属性:
  30. * value:用于指定其他配置类的字节码
  31. * 当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
  32. * PropertySource
  33. * 作用:用于指定properties文件的位置
  34. * 属性:
  35. * value:指定文件的名称和路径。
  36. * 关键字:classpath,表示类路径下
  37. */
  38. @Configuration
  39. @Import(JdbcConfig.class)
  40. @ComponentScan("com.itheima")
  41. @PropertySource("classpath:JdbcConfig.properties")
  42. public class SpringConfigration {
  43. }

8 Spring整合Junit

  1. package com.itheima.test;
  2. import com.itheima.domain.Account;
  3. import com.itheima.service.AccountService;
  4. import config.SpringConfigration;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;
  12. import org.springframework.test.context.ContextConfiguration;
  13. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  14. import java.util.List;
  15. /**
  16. * 使用Junit单元测试我们的配置
  17. * Spring整合junit的配置
  18. * 1. 导入Spring整合Junit的jar(坐标)
  19. * 2. 使用Junit提供的注解, 把原有的main方法给替换了, 替换成Spring提供的
  20. * @Runwith
  21. * 3. 告知Spring的运行器, spring的IOC创建是基于xml还是注解的, 并且说明位置
  22. * @ContextConfiguration
  23. * Location:指定xml文件的位置, 加上classpath关键字, 表示在类路径下
  24. * classes: 指定注解类所在的位置,当不使用 xml 配置时,需要用此属性指定注解类的位置。
  25. * 当我们使用spring 5.x版本的时候, 要求Junit的jar必须是4.12及以上
  26. *
  27. */
  28. @RunWith(SpringJUnit4ClassRunner.class)
  29. @ContextConfiguration(classes = SpringConfigration.class)
  30. public class AccountServiceTest {
  31. /*private ApplicationContext ac = null;*/
  32. @Autowired
  33. private AccountService as=null;
  34. /* @Before
  35. public void init() {
  36. //1. 使用注释配置时
  37. ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
  38. //2. 得到业务层对象
  39. as = ac.getBean("accountService", AccountService.class);
  40. }*/
  41. @Test
  42. public void testFindAll() {
  43. //1. 使用xml配置时,使用该方法
  44. // ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  45. //3. 执行方法
  46. List<Account> accounts = as.findAllAccount();
  47. for (Account account : accounts) {
  48. System.out.println(account);
  49. }
  50. }
  51. }

9 @Autowired和@Bean的原理

  1. 那么使用@Autowired的原理是什么?
  2.   其实在启动spring IoC时,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到@Autowied@Resource(是CommonAnnotationBeanPostProcessor后置处理器处理的)或@Inject时,就会在IoC容器自动查找需要的bean,并装配给该对象的属性
  3. <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  4.   
  5. 注意事项:
  6.   在使用@Autowired时,首先在容器中查询==对应类型==的bean
  7.     如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据
  8.     如果查询的结果不止一个,那么@Autowired会根据名称来查找。
  9.     如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false
  1. @Bean 基础声明
  2. Spring@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。
  3. SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。
  1. 注解分为两类:
  2. 1、一类是使用Bean,即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;比如@Autowired , @Resource,可以通过byTYPE@Autowired)、byNAME@Resource)的方式获取Bean
  3. 2、一类是注册Bean,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一起,把对象、属性、方法完美组装。

10 Spring AOP

AOP(Aspect Oriented Programming):面向切面编程

以下内容参考:SpringAOP

AOP要做的三件事:

  • 在哪里切入,也就是权限校验等非业务操作在哪些业务操作中执行
  • 在什么时候切入,是业务代码执行前还是执行后
  • 切入后做什么事,比如权限校验、日志的记录

体系梳理为下图:
Spring - 图2

概念详解:

  • PointCut:切点,决定处理如权限校验、日志记录等在何处切入到业务代码中(即织入weaving切面)。分为execution方式和annotation方式。前者可以使用路径表达式指定哪些类织入切面,后者可以指定被哪些注解修饰的代码织入切面
  • Advice:处理,包括了处理的时机和处理内容,处理内容就是要做什么事。处理时机就是在什么时机执行处理内容,分为前置处理(即业务代码执行前)、后置处理(业务代码执行后)等
  • Aspect:切面,即PonitCut和Advice
  • Joint point:连接点,程序执行的一个点。例如,一个方法的执行或者一个异常的处理,在SpringAOP中,一个连接点总是代表一个方法的执行
  • Weaving:织入,就是通过动态代理,在目标对象方法中执行处理内容的过程

Spring - 图3

10.1 动态代理

  1. package com.itheima.proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. /**
  6. * 模拟一个消费者
  7. */
  8. public class Client {
  9. public static void main(String[] args) {
  10. final Producer producer = new Producer();
  11. /*producer.saleProduct(10000f);*/
  12. /*
  13. 动态代理:(和装饰者模式的区别)
  14. 特点:字节码随用随创建,随用随加载
  15. 作用:不修改源码的基础上,对方法增强
  16. 分类:
  17. 1. 基于接口的动态代理
  18. 2. 基于子类的动态代理
  19. 基于接口的动态代理:
  20. 涉及的类:Proxy
  21. 提供者:JDK官方
  22. 如何创建代理对象:
  23. 使用Proxy类中的newProxyInstance方法
  24. 创建代理对象的要求:
  25. 被代理类最少实现一个接口,如果没有则不能使用
  26. newProxyInstance方法的参数:
  27. ClassLoader:类加载器
  28. 他是用于加载代理对象字节码的,和被代理对象使用相同的类加载器.固定写法
  29. Class[]:字节码数组
  30. 他是用于代理对象和被代理对象有相同的方法。(即继承同一个接口)
  31. InvocationHandler:用于提供增强的代码
  32. 他是让我们写如何代理,我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不必须
  33. 此接口的实现类,都是谁用谁写
  34. */
  35. IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
  36. new InvocationHandler() {
  37. /**
  38. * 作用:执行被代理对象的任何接口方法都会经过该方法
  39. * 方法参数的含义
  40. * @param proxy 代理对象的引用
  41. * @param method 当前执行的方法
  42. * @param args 当前执行方法所需的参数
  43. * @return 和被代理对象方法有相同的返回值
  44. * @throws Throwable
  45. */
  46. @Override
  47. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  48. //提供增强的代码
  49. Object returnValue = null;
  50. //1. 获取方法执行的参数
  51. Float money = (Float) args[0];
  52. //2. 判断当前方法是不是销售
  53. if ("saleProduct".equals(method.getName())) {
  54. returnValue = method.invoke(producer, money * 0.8f);
  55. }
  56. return returnValue;
  57. }
  58. });
  59. proxyProducer.saleProduct(10000f);
  60. }
  61. }

10.2 AOP的XML配置

bean.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!--配置spring的IOC,把service对象配置进来-->
  10. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
  11. <!--spring中基于XML的AOP配置步骤:
  12. 1. 把通知bean也交给spring来管理
  13. 2. 使用aop:config标签,表明开始AOP的配置
  14. 3. 使用aop:aspect标签,表明配置切面
  15. id: 属性是给切面一个唯一的标识
  16. ref属性:是指定通知类bean的id
  17. 4. 在aop:aspect标签的内部使用对应的标签来配置通知的类型
  18. 我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知
  19. aop:before: 表示配置前置通知
  20. method属性:用于指定Logger类中哪个方法是前置通知 // printLog()
  21. pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
  22. 5. 切入点表达式的写法:
  23. 关键字:execution(表达式)
  24. 表达式:
  25. 访问修饰符 返回值 包名.包名.包名....类名.方法名(参数列表)
  26. 标准的表达式写法:
  27. public void com.itheima.service.impl.AccountServiceImpl.saveAccount()
  28. 访问修饰符可以省略
  29. void com.itheima.service.impl.AccountServiceImpl.saveAccount()
  30. 返回值可以使用通配符表示任意返回值
  31. * com.itheima.service.impl.AccountServiceImpl.saveAccount()
  32. 包名可以使用通配符,表示任意包, 但是有几级包, 就需要写几个*
  33. * *.*.*.*.AccountServiceImpl.saveAccount()
  34. 包名可以使用..表示当前包及其子包
  35. * *..AccountServiceImpl.saveAccount()
  36. 类名和方法名都可以使用*来实现通配
  37. * *..*.*()
  38. 参数列表:
  39. 可以直接写数据类型:
  40. 基本类型直接写名称 int
  41. 引用类型写包名.类名的方式 java.lang.String
  42. 可以使用通配符, 表示任意类型, 但是必须有参数
  43. 可以使用..表示有无参数均可, 有参数可以是任意类型
  44. 全通配写法:
  45. * *..*.*(..)
  46. 实际开发中, 切入点表达式的通常写法:
  47. 切到业务层实现类下的所有方法
  48. * com.itheima.service.impl.*.*(..)
  49. -->
  50. <!--配置Logger类-->
  51. <bean id="logger" class="com.itheima.utils.Logger"></bean>
  52. <!--配置AOP-->
  53. <aop:config>
  54. <!--配置切面-->
  55. <aop:aspect id="logAdvice" ref="logger">
  56. <!--配置通知的类型且建立通知方法和切入点方法的关联-->
  57. <aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.AccountServiceImpl.saveCount(..))"></aop:before>
  58. </aop:aspect>
  59. </aop:config>
  60. </beans>

main文件

  1. package com.itheima.test;
  2. import com.itheima.service.AccountService;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. /**
  6. * 测试AOP的配置
  7. */
  8. public class AOPTest {
  9. public static void main(String[] args) {
  10. //1. 获取容器
  11. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  12. //2. 获取对象
  13. AccountService as = (AccountService) ac.getBean("accountService");
  14. //3. 执行方法
  15. as.saveAccount(); // 只会在该方法之前执行printLog()方法
  16. as.deleteAccount();
  17. as.updateAccount(1);
  18. }
  19. }

环绕通知配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!--配置spring的IOC,把service对象配置进来-->
  10. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
  11. <!--配置Logger类-->
  12. <bean id="logger" class="com.itheima.utils.Logger"></bean>
  13. <!--配置AOP-->
  14. <aop:config>
  15. <!--配置切入点表达式 id属性:用于指定表达式的唯一标识
  16. expression属性:用于指定表达式内容
  17. 此标签写在aop:aspect标签内部只能当前切面使用
  18. 它还可以写在aop:aspect外面,此时就变成了所有切面可用, 提升了复用性
  19. -->
  20. <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>
  21. <!--配置切面-->
  22. <aop:aspect id="logAdvice" ref="logger">
  23. <!--前置通知: 在切入点方法执行之前执行
  24. <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
  25. &lt;!&ndash;后置通知:在切入点方法执行之后执行&ndash;&gt;
  26. <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
  27. &lt;!&ndash;异常通知:在切入点方法执行产生异常之后执行&ndash;&gt;
  28. <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
  29. &lt;!&ndash;最终通知:无论切入点方法是否正常执行它都会在其后边执行&ndash;&gt;
  30. <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>-->
  31. <!--配置环绕通知 详细的注释请看Logger类中-->
  32. <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
  33. </aop:aspect>
  34. </aop:config>
  35. </beans>

code

  1. package com.itheima.utils;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. /**
  4. * 用于记录日志的工具类,它里面提供了公共的代码
  5. */
  6. public class Logger {
  7. /**
  8. * 前置通知
  9. */
  10. public void beforePrintLog() {
  11. System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了");
  12. }
  13. /**
  14. * 后置通知
  15. */
  16. public void afterReturningPrintLog() {
  17. System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了");
  18. }
  19. /**
  20. * 异常通知
  21. */
  22. /* public void afterThrowingPrintLog() {
  23. System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了");
  24. }*/
  25. /**
  26. * 最终通知
  27. */
  28. public void afterPrintLog() {
  29. System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了");
  30. }
  31. /**
  32. * 环绕通知
  33. * 问题:
  34. * 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
  35. * 分析:
  36. * 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有
  37. * 解决:
  38. * Spring框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于调用切入点方法
  39. * 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
  40. *
  41. * spring中的环绕通知:
  42. * 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
  43. */
  44. public Object aroundPrintLog(ProceedingJoinPoint pjp) {
  45. Object rtValue = null;
  46. try {
  47. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……前置");
  48. //得到方法执行所需的参数
  49. Object[] args = pjp.getArgs();
  50. //明确调用业务层方法(切入点方法)
  51. // System.out.println(args.length);
  52. rtValue = pjp.proceed(args);
  53. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……后置");
  54. return rtValue;
  55. } catch (Throwable throwable) {
  56. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……异常");
  57. throw new RuntimeException(throwable);
  58. } finally {
  59. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……最终");
  60. }
  61. }
  62. }

10.3 AOP的注解配置

XML:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!--配置spring创建容器时要扫描的包-->
  13. <context:component-scan base-package="com.itheima"></context:component-scan>
  14. <!--配置spring开启注解AOP的支持-->
  15. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  16. </beans>

Logger

  1. package com.itheima.utils;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.*;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * 用于记录日志的工具类,它里面提供了公共的代码
  7. */
  8. @Component("logger") // 将该类注入到IOC容器中
  9. @Aspect //表示当前类是一个切面类
  10. public class Logger {
  11. @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
  12. private void pt1() {};
  13. /**
  14. * 前置通知
  15. */
  16. // @Before("pt1()")
  17. public void beforePrintLog() {
  18. System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了");
  19. }
  20. /**
  21. * 后置通知
  22. */
  23. // @AfterReturning("pt1()")
  24. public void afterReturningPrintLog() {
  25. System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了");
  26. }
  27. /**
  28. * 异常通知
  29. */
  30. // @AfterThrowing("pt1()")
  31. public void afterThrowingPrintLog() {
  32. System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了");
  33. }
  34. /**
  35. * 最终通知
  36. */
  37. // @After("pt1()")
  38. public void afterPrintLog() {
  39. System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了");
  40. }
  41. /**
  42. * 环绕通知
  43. * 问题:
  44. * 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
  45. * 分析:
  46. * 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有
  47. * 解决:
  48. * Spring框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于调用切入点方法
  49. * 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
  50. *
  51. * spring中的环绕通知:
  52. * 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
  53. */
  54. @Around(("pt1()"))
  55. public Object aroundPrintLog(ProceedingJoinPoint pjp) {
  56. Object rtValue = null;
  57. try {
  58. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……前置");
  59. //得到方法执行所需的参数
  60. Object[] args = pjp.getArgs();
  61. //明确调用业务层方法(切入点方法)
  62. rtValue = pjp.proceed(args);
  63. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……后置");
  64. return rtValue;
  65. } catch (Throwable throwable) {
  66. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……异常");
  67. throw new RuntimeException(throwable);
  68. } finally {
  69. System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……最终");
  70. }
  71. }
  72. }

11 Spring中的事务处理

JavaEE进行分层开发,事务处理位于业务层

  • Spring框架提供了一组事务控制的接口
  • spring的事务控制都是基于AOP的,既可以使用编程的方式实现,也可以使用配置的方式

事务管理主要包括:

  • 开启事务:beginTransaction()
  • 提交事务:commit(),这时候成功的数据才会序列化到硬盘上,解决多线程操作数据的问题(银行取钱)
  • 回滚事务:rollback(),回滚到上次代码没有出错的数据状态
  • 释放连接:release(),还回连接池中

11.1 事务的XML配置

  1. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
  2. <!--注入Dao-->
  3. <property name="accountDao" ref="accountDao"></property>
  4. <!--注入事务管理器, 事务控制一般是在业务层进行-->
  5. <property name="txManager" ref="txManager"></property>
  6. </bean>
  7. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl>">
  8. <!--注入QueryRunner-->
  9. <property name="runner" ref="runner"></property>
  10. <!--注入ConnectionUtils-->
  11. <property name="connectionUtils" ref="connectionUtils"></property>
  12. </bean>
  13. <!--配置QueryRunner对象-->
  14. <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
  15. <!--配置数据源-->
  16. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  17. <!--连接数据库的必备信息-->
  18. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  19. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
  20. <property name="user" value="root"></property>
  21. <property name="password" value="root"></property>
  22. </bean>
  23. <!--配置connection的工具类 ConnectionUtils-->
  24. <bean id="connectionUtils" class="com.itheima.utils.ConnectionUtils">
  25. <!--注入数据源-->
  26. <property name="dataSource" ref="dataSource"></property>
  27. </bean>
  28. <!--配置事务管理器-->
  29. <bean id="txManager" class="com.itheima.utils.TransactionManager">
  30. <property name="connectionUtils" ref="connectionUtils"></property>
  31. </bean>
  32. <!--配置AOP-->
  33. <aop:config>
  34. <!--配置通用切入点表达式-->
  35. <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>
  36. <aop:aspect id="txAdvice" ref="txManager">
  37. <!--配置前置通知:开启事务-->
  38. <aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
  39. <!--配置后置通知:提交事务-->
  40. <aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
  41. <!--配置异常通知:回滚事务-->
  42. <aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
  43. <!--配置最终通知:释放连接-->
  44. <aop:after method="release" pointcut-ref="pt1"></aop:after>
  45. </aop:aspect>
  46. </aop:config>

事务管理类

  1. package com.itheima.utils;
  2. import java.sql.SQLException;
  3. /**
  4. * 和事务管理相关的工具类,它包含了:开启事务,提交事务,回滚事务,和释放连接
  5. */
  6. public class TransactionManager {
  7. private ConnectionUtils connectionUtils;
  8. public void setConnectionUtils(ConnectionUtils connectionUtils) {
  9. this.connectionUtils = connectionUtils;
  10. }
  11. /**
  12. * 开启事务
  13. */
  14. public void beginTransaction() {
  15. try {
  16. connectionUtils.getThreadConnection().setAutoCommit(false);
  17. } catch (SQLException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. /**
  22. * 提交事务
  23. */
  24. public void commit() {
  25. try {
  26. connectionUtils.getThreadConnection().commit();
  27. } catch (SQLException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. /**
  32. * 回滚事务
  33. */
  34. public void rollback() {
  35. try {
  36. connectionUtils.getThreadConnection().rollback();
  37. } catch (SQLException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. /**
  42. * 释放连接
  43. */
  44. public void release() {
  45. try {
  46. connectionUtils.getThreadConnection().close(); //还回连接池中
  47. connectionUtils.removeConnection();
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }

11.2 事务的注解配置

通过使用进程连接点(ProceedingJoinPoint)处理

TransactionManager :都是在 arroundAdvice 中调用其余的方法

  1. package com.itheima.utils;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.*;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Component;
  6. import java.sql.SQLException;
  7. /**
  8. * 和事务管理相关的工具类,它包含了:开启事务,提交事务,回滚事务,和释放连接
  9. */
  10. @Component("txManager")
  11. @Aspect
  12. public class TransactionManager {
  13. @Autowired
  14. private ConnectionUtils connectionUtils;
  15. @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
  16. private void pt1() {}
  17. /**
  18. * 开启事务
  19. */
  20. public void beginTransaction() {
  21. try {
  22. connectionUtils.getThreadConnection().setAutoCommit(false);
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. /**
  28. * 提交事务
  29. */
  30. public void commit() {
  31. try {
  32. connectionUtils.getThreadConnection().commit();
  33. } catch (SQLException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. /**
  38. * 回滚事务
  39. */
  40. public void rollback() {
  41. try {
  42. connectionUtils.getThreadConnection().rollback();
  43. } catch (SQLException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. /**
  48. * 释放连接
  49. */
  50. public void release() {
  51. try {
  52. connectionUtils.getThreadConnection().close(); //还回连接池中
  53. connectionUtils.removeConnection();
  54. } catch (SQLException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. @Around("pt1()") // 事务的控制是环绕通知
  59. public Object arroundAdvice(ProceedingJoinPoint pjp) {
  60. Object rtValue = null;
  61. try{
  62. //1. 获取参数
  63. Object[] args = pjp.getArgs();
  64. //2. 开启事务
  65. this.beginTransaction();
  66. //3. 执行方法
  67. rtValue = pjp.proceed(args);
  68. //4. 提交事务
  69. this.commit();
  70. //返回结果
  71. return rtValue;
  72. } catch (Throwable e) {
  73. //5. 回滚事务
  74. this.rollback();
  75. throw new RuntimeException(e);
  76. } finally {
  77. //6. 释放资源
  78. this.release();
  79. }
  80. }
  81. }

12 SpringJdbc

一般配置数据源的方式

  1. public static void main(String[] args) {
  2. //准备数据源,spring的内置数据源
  3. DriverManagerDataSource ds = new DriverManagerDataSource();
  4. ds.setDriverClassName("com.mysql.jdbc.Driver");
  5. ds.setUrl("jdbc:mysql://localhost:3306/eesy");
  6. ds.setUsername("root");
  7. ds.setPassword("root");
  8. //1. 创建对象
  9. JdbcTemplate jt = new JdbcTemplate();
  10. //给jt设置数据源
  11. jt.setDataSource(ds);
  12. //2. 执行操作
  13. jt.execute("insert into account(name ,money) values('ccc', 1000)");
  14. }

使用注解配置,通过反射获得

  1. <!--配置业务层-->
  2. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
  3. <property name="accountDao" ref="accountDao"></property>
  4. </bean>
  5. <!--配置账户的持久层-->
  6. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
  7. <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
  8. <property name="dataSource" ref="dataSource"></property>
  9. </bean>
  10. <!--配置数据源-->
  11. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  12. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  13. <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
  14. <property name="username" value="root"></property>
  15. <property name="password" value="root"></property>
  16. </bean>
  1. /**
  2. * JdbcTemplate的最基本用法CRUD
  3. */
  4. public class JdbcTemplateDemo3 {
  5. public static void main(String[] args) {
  6. //1. 获取容器
  7. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  8. //2. 获取对象
  9. JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
  10. //3. 执行操作
  11. //保存
  12. jt.update("insert into account(name, money) values(?, ?)", "eee", 333f);
  13. //更新
  14. jt.update("update account set name = ?, money = ? where id = ? ", "test", 4567, 1);
  15. //删除
  16. jt.update("delete from account where id = ?", 2);
  17. //查询所有
  18. // List<Account> accounts = jt.query("select * from account where money ? ?", new AccountRowMapper(), 1000f);
  19. // List<Account> accounts = jt.query("select * from account where money > ?", new BeanPropertyRowMapper<Account>(Account.class), 1000f);
  20. // for (Account account : accounts) {
  21. // System.out.println(account);
  22. // }
  23. //查询一个
  24. /* List<Account> accounts= jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);
  25. //这波操作有点6
  26. System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));*/
  27. //查询返回一行一列(使用聚合函数,但是不含Group by子句)
  28. Long count = jt.queryForObject("select count(*) from account where money > ?", Long.class, 1000f);
  29. System.out.println(count);
  30. }
  31. /**
  32. * 定义Account的封装策略
  33. */
  34. static class AccountRowMapper implements RowMapper<Account> {
  35. /**
  36. * 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
  37. * @param resultSet
  38. * @param i
  39. * @return
  40. * @throws SQLException
  41. */
  42. public Account mapRow(ResultSet resultSet, int i) throws SQLException {
  43. Account account = new Account();
  44. account.setId(resultSet.getInt("id"));
  45. account.setName(resultSet.getString("name"));
  46. account.setMoney(resultSet.getFloat("money"));
  47. return account;
  48. }
  49. }
  50. }

13 完整的一个Spring的XML配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/tx
  10. http://www.springframework.org/schema/tx/spring-tx.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd">
  13. <!--配置业务层-->
  14. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
  15. <property name="accountDao" ref="accountDao"></property>
  16. </bean>
  17. <!--配置账户的持久层-->
  18. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
  19. <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
  20. <property name="dataSource" ref="dataSource"></property>
  21. </bean>
  22. <!--配置数据源-->
  23. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  24. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  25. <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
  26. <property name="username" value="root"></property>
  27. <property name="password" value="root"></property>
  28. </bean>
  29. <!--spring中基于xml的声明式事务控制配置步骤:
  30. 1. 配置事务管理器
  31. 2. 配置事务通知
  32. 此时我们要导入事务的约束 tx名称空间和约束,同时也需要aop的
  33. 使用tx:advice标签配置事务通知
  34. 属性:
  35. id:给事务通知起一个唯一标识
  36. transaction-manager:给事务通知提供一个事务管理器引用
  37. 3. 配置AOP中的通用切入点表达式
  38. 4. 建立事务通知和切入点表达式的对应关系
  39. 5. 配置事务的属性
  40. 是在事务的通知tx:advice标签的内部
  41. -->
  42. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  43. <property name="dataSource" ref="dataSource"></property>
  44. </bean>
  45. <!--配置事务的通知-->
  46. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  47. <!--配置事务的属性
  48. isolation: 用于指定事务的隔离级别,默认值式DEFAULT,
  49. propagation:用于指定事务的传播行为。默认值式REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
  50. read-only:用于指定事务是否只读,只有查询方法才能设置为true,默认值式false,表示读写
  51. timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位
  52. rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚
  53. no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,当产生其他异常时事务回滚,没有默认值,表示任何异常都回滚
  54. -->
  55. <tx:attributes>
  56. <tx:method name="*" propagation="REQUIRED" read-only="false"/>
  57. <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
  58. </tx:attributes>
  59. </tx:advice>
  60. <!--配置aop-->
  61. <aop:config>
  62. <!--配置切入点表达式-->
  63. <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
  64. <!--建立切入点表达式和事务通知的对应关系-->
  65. <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
  66. </aop:config>
  67. </beans>