1 程序的耦合
/*** 程序的耦合:* 耦合:程序间的依赖关系* 包括:类之间的依赖* 方法之间的依赖* 解耦:降低程序间的依赖关系* 实际开发中,应该做到:编译器不依赖,运行时才依赖* 解决的思路:* 第一步:使用反射来创建对象,而避免使用new关键字* 第二步:通过读取配置文件,获取要创建的对象全限定类名*/
2 什么是Bean???
- Bean:在计算机英语中,由可重用组件的含义
- JavaBean:用java语言编写的,可重用组件, javaBean >= 实体类
Bean的创建有三种方式
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--把对象的创建交给是spring来管理--><!--sping对bean的管理细节1. 创建bean的三种方式2. bean对象的作用范围3. bean对象的生命周期--><!--创建bean的三种方式--><!--第一种方式:使用默认构造函数创建。在spring的配置文件中,使用bean标签,配以id和class属性之后,且没有其他属性和标签时。采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建--><!--<bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl"></bean>--><!--第二种方式:使用普通工厂中的方法创建对象,或者使用某个类中的方法创建对象,并存入spring容器--><!--<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean><bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>--><!--第三种方式:使用工厂中的静态方法创建对象,使用某个类中的静态方法创建对象,并存入spring容器--><!--<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>--><!--bean的作用范围调整bean标签的scope属性:用于指定bean的作用范围取值:singleton:单例(默认值)prototype:多例的request:作用于web应用的请求范围session:作用于web应用的会话范围global-session:作用域集群环境的会话范围(全局会话范围),当不是集群环境时,他就是session--><!--<bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="singleton"></bean>--><!--bean对象的生命周期单例对象:出生:当容器创建对象时出生活着:只要容器还在,对象一直活着死亡:容器销毁,对象消亡总结:单例对象的生命周期和容器相同多例对象:出生:当我们使用对象时,spring框架为我们创建活着:对象只要在使用过程中就一直活着死亡:当对象长时间不用,且没有别的对象引用时,由Java的垃圾回收机制处理--><bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="singleton"init-method="init" destroy-method="destory"></bean></beans>
3 工厂类的产生
package com.itheima.factory;import jdk.internal.util.xml.impl.Input;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.Properties;/*** 一个创建Bean对象的工厂** Bean:在计算机英语中,由可重用组件的含义* JavaBean:用java语言编写的,可重用组件* javaBean >= 实体类* 它就是创建我们的service和dao对象的* 第一个:需要一个配置文件来配置我们的service和dao* 配置的内容:唯一标志=全限定类名(key=value)* 第二个:通过读取配置文件中的配置内容,反射创建对象* 配置文件可以是xml也可以是properties*/public class BeanFactory {//定义一个Properties对象private static Properties props;//定义一个Map,用于存放我们要创建的对象,我们把它称之为容器private static Map<String, Object> beans;//使用静态代码块为Properties对象赋值static {//实例化try {props = new Properties();//获取propertoes文件的流对象InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");props.load(in);//实例化容器beans = new HashMap<String, Object>();//取出配置文件中所有的keyEnumeration keys = props.keys();//遍历枚举while (keys.hasMoreElements()) {//取出每个keyString key = keys.nextElement().toString();//根据key获取valueString beanPath = props.getProperty(key);//反射创建对象Object value = Class.forName(beanPath).newInstance();//把key和value存入容器中beans.put(key, value);}} catch (Exception e) {e.printStackTrace();}}/*** 根据Bean的名称获取Bean对象* @param beanName* @return*//*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;}*/public static Object getBean(String beanName) {return beans.get(beanName);}}
4 ApplicationContext和BeanFactory的区别
- 前者是后者的子接口,BeanFactory是Spring容器中的顶层接口
- 创建对象的时间不同
- ApplicationContext:只要一读取配置文件,默认情况下就会创建对象
- BeanFactory:什么时候使用什么时候创建对象
* ApplicationContext的三个常用实现类:* ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下, 不在的活加载不了* FileSystemXmlApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)* AnnotationConfigApplicationContext:用于读取注解创建容器的** 核心容器的两个接口引发的问题:* ApplicationContext: 单例对象适用 采用此接口* 他在构建核心容器时,创建对象采取的策略是采用立即加载的方式,也就是说,只要一读取完配置文 件马上就创建配置文件中的配置对象。* BeanFatory: 多例对象适用* 他在构建核心容器时,创建对象采取的策略是采用延迟加载的方式,也就是说,什么时候根据id获取 了对象,什么时候才是真正的创建对象public static void main(String[] args) {//1. 获取核心容器对象, 单例在此处便实例化类对象了, prototype多例则在下方的getBean时才会实例化类对象, Object value = Class.forName(beanPath).newInstance();// ApplicationContext和BeanFactory是有区别的: 前者是后者的子接口ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");// ApplicationContext ac = new FileSystemXmlApplicationContext("D:\\Learning_Material\\JAVA\\Black_house\\day01_03Spring\\src\\main\\resources\\bean.xml");//2. 根据id获取bean对象, 多态, 强转AccountService as1 = (AccountService) ac.getBean("accountService");AccountService as2 = (AccountService) ac.getBean("accountService");AccountDao adao = ac.getBean("accountDao", AccountDao.class);System.out.println(as1);System.out.println(as2);System.out.println(adao);// as.saveAccount();}
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--把对象的创建交给是spring来管理--><bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" scope="prototype"></bean><bean id="accountDao" class="com.itheima.dao.Impl.AccountDaoImpl"></bean></beans>
可以看出,accountService是一个多例的Bean对象
单例、多例的区别:SpringIOC容器中的bean默认都是单例的,指定多例需要使用scope="prototype"
- 单例:在SpringIOC容器中只会实例化一个bean对象,后续的请求都公用这个请求
- 优点:减少新生成实例的消耗、减少jvm垃圾回收的次数、可以快速的获取到bean
- 缺点:在多并发的场景下,线程不安全(可使用线程同步机制、或者使用ThreadLocal)
- 多例:每次调用都会创建一个新的bean对象,对象不会共享
4.1 BeanFactory和FactoryBean的区别与联系
- 两者都是接口;
- BeanFactory主要是用来创建Bean和获得Bean的;
- FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象;
- 通过BeanFactory和beanName获取bean时,如果beanName不加&则获取到对应bean的实例;如果beanName加上&,则获取到FactoryBean本身的实例
- FactoryBean 通常是用来创建比较复杂的bean(如创建mybatis的SqlSessionFactory很复杂),一般的bean 直接用xml配置即可,但如果创建一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean。
5 依赖注入
三种方式
构造函数注入 :
<!--构造函数注入:使用的标签:constructor-arg标签出现的位置:bean标签的内部标签中的属性:type:用于指定要注入的数据数据类型,改数据类型也是构造函数中某个或某些参数的类型index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置从0开始name: 用于指定给构造函数中指定名称的参数赋值value: 用于提供基本类型和String类型的数据ref:用于指定其他的bean类型数据,它指的就是在是spring的IOC核心容器中出现过的bean对象优势:在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功弊端:改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供--><bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl" ><constructor-arg name="name" value="test"></constructor-arg><constructor-arg name="age" value="18"></constructor-arg><constructor-arg name="birthday" ref="now"></constructor-arg></bean><!--配置一个日期对象--><bean id="now" class="java.util.Date"></bean>
Set方法注入(常用) :
<!--set方法注入涉及的标签:property出现的位置:bean标签的内部标签的属性:name: 用于指定给构造函数中指定名称的参数赋值,即pojo类成员变量set方法名后面的字符串(大写变小写)value: 用于提供基本类型和String类型的数据ref:用于指定其他的bean类型数据,它指的就是在是spring的IOC核心容器中出现过的bean对象优势:创建对象没有明确限制,可以直接使用默认构造函数弊端:如果有某个成员必须有值,则获取对象set方法有可能没法执行--><bean id="accountService2" class="com.itheima.service.Impl.AccountServiceImpl2"><property name="name" value="TEST"></property><property name="age" value="13"></property><property name="birthday" ref="now"></property></bean>
使用注解注入 :
<!--复杂类型的注入/集合类型的注入用于给list结构集合注入的标签:list array set用于给Map结构集合注入的标签:map props结构相同,标签可以互换--><bean id="accountService3" class="com.itheima.service.Impl.AccountServiceImpl3"><property name="myStrs"><array><value>AAA</value><value>BBB</value><value>CCC</value></array></property><property name="myList"><list><value>AAA</value><value>BBB</value><value>CCC</value></list></property><property name="mySet"><set><value>AAA</value><value>BBB</value><value>CCC</value></set></property><property name="myMap"><map><entry key="testA" value="aaa"></entry><entry key="testB"><value>BBB</value></entry></map></property><property name="myProps"><props><prop key="testC">ccc</prop><prop key="testD">ddd</prop></props></property></bean>
6 注解详解
package com.itheima.service.Impl;import com.itheima.dao.AccountDao;import com.itheima.dao.Impl.AccountDaoImpl;import com.itheima.domain.Account;import com.itheima.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;/*** 业务层实现类* 曾经xml的配置* <bean id="accountService" class="com.itheima.service.Impl.AccountServiceImpl"* scope="" init-method="" destory0method="">* <property name="" value="" / ref=""></property>* </bean>** 用于创建对象的* 他们的作用就和XMl配置文件中编写一个<bean>标签实现的功能是一样的* @Component:* 作用:用于把当前类对象,存入spring容器中* 属性:* value:用于指定bean的id。当我们不写时,它的默认值时当前类名,且首字母改小写* Controller:一般用在表现层* Service:一般用在业务层* Respository:一般用在持久层* 以上三个注解他们的作用和属性于Component是一摸一样。* 它们三个是spring框架为我们提供明确的三层使用的注解,使我们三层对象更加清晰** 用于注入数据的* 他们的作用就和在XMl配置文件中的bean标签中写一个<property>标签的作用是一样的* Autowired:* 作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配(不区分大小写??),就可以注入成功* 如果IOC容器中,没有任何bean类型和要注入的变量类型匹配,则报错* 出现位置:* 可以是变量上,也可以是方法上* 细节:* 在使用注解注入时,set方法就不是必须的了* Qualifier:* 作用:在按照类中注入的基础之上,再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以* 属性:* value:用于指定注入bean的id* Resource:* 作用:直接按照bean的id注入,它可以独立使用* 属性:* name:用于指定bean的id* 以上三个注解都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现* 另外,集合类型的注入只能通过XML来实现** Value注解:* 作用:用于注入基本类型和String类型的数据* 属性:* value:用于指定数据的值,它可以使用spring中的SpEL(也即是Spring的EL表达式)* SpEL的写法:${表达式}** 用于改变作用范围的* 他们的作用就和在bean标签中使用的scope实行实现的功能是一样的* Scope* 作用:用于指定bean的作用范围* 属性:* value:指定范围的取值,常用取值:singleton(单例) prototype(多例)* 和生命周期相关的* 他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的* PreDestroy* 作用:用于指定销毁方法* PostConstruct* 作用:用于指定初始化方法*/@Service(value = "accountService") // 即指定对应bean的id为accountServicepublic class AccountServiceImpl implements AccountService {// 当以下的注解被注释掉后,默认使用的是相对应的配置文件// @Autowired// @Qualifier("accountDao1")private AccountDao accountDao;public void saveAccount() {accountDao.saveAccount();}public List<Account> findAllAccount() {return null;}public void setAccountDao(AccountDaoImpl accountDao) {}}
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的选择问题

7 配置类
package config;import com.mchange.v2.c3p0.ComboPooledDataSource;import org.apache.commons.dbutils.QueryRunner;import org.springframework.context.annotation.*;import org.springframework.stereotype.Component;import javax.sql.DataSource;import java.beans.PropertyVetoException;/*** 该类是一个配置类,他的作用是和bean.xml是一样的* spring中的新注解* Configuration* 作用:指定当前类是一个配置类,来代替原先的XML配置文件* 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写* ComponentScan:* 作用:用于通过注解指定spring在创建容器时要扫描的包* 属性:* value:它和basePackages的作用时一样的。都是用于只当创建容器时要扫描的包* 我们使用此注解就等同于在xml中配置了:<context:component-scan base-package="com.itheima"></context:component-scan>* Bean注解:* 作用:用于把当前方法的返回值(对象)作为bean对象存入spring的ioc容器中* 属性:* name:用于指定bean的id。当不写时,默认值是当前方法的名称* 细节:* 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象该注解只能写在方法上和@Component的区别,@Bean作用在方法对象上,后者作用在类对象上* Import:* 作用:用于导入其他的配置类* 属性:* value:用于指定其他配置类的字节码* 当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类* PropertySource* 作用:用于指定properties文件的位置* 属性:* value:指定文件的名称和路径。* 关键字:classpath,表示类路径下*/@Configuration@Import(JdbcConfig.class)@ComponentScan("com.itheima")@PropertySource("classpath:JdbcConfig.properties")public class SpringConfigration {}
8 Spring整合Junit
package com.itheima.test;import com.itheima.domain.Account;import com.itheima.service.AccountService;import config.SpringConfigration;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;/*** 使用Junit单元测试我们的配置* Spring整合junit的配置* 1. 导入Spring整合Junit的jar(坐标)* 2. 使用Junit提供的注解, 把原有的main方法给替换了, 替换成Spring提供的* @Runwith* 3. 告知Spring的运行器, spring的IOC创建是基于xml还是注解的, 并且说明位置* @ContextConfiguration* Location:指定xml文件的位置, 加上classpath关键字, 表示在类路径下* classes: 指定注解类所在的位置,当不使用 xml 配置时,需要用此属性指定注解类的位置。* 当我们使用spring 5.x版本的时候, 要求Junit的jar必须是4.12及以上**/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfigration.class)public class AccountServiceTest {/*private ApplicationContext ac = null;*/@Autowiredprivate AccountService as=null;/* @Beforepublic void init() {//1. 使用注释配置时ac = new AnnotationConfigApplicationContext(SpringConfigration.class);//2. 得到业务层对象as = ac.getBean("accountService", AccountService.class);}*/@Testpublic void testFindAll() {//1. 使用xml配置时,使用该方法// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//3. 执行方法List<Account> accounts = as.findAllAccount();for (Account account : accounts) {System.out.println(account);}}}
9 @Autowired和@Bean的原理
那么使用@Autowired的原理是什么?其实在启动spring IoC时,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到@Autowied、@Resource(是CommonAnnotationBeanPostProcessor后置处理器处理的)或@Inject时,就会在IoC容器自动查找需要的bean,并装配给该对象的属性<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>注意事项:在使用@Autowired时,首先在容器中查询==对应类型==的bean如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据如果查询的结果不止一个,那么@Autowired会根据名称来查找。如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false
@Bean 基础声明Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。
注解分为两类:1、一类是使用Bean,即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;比如@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean;2、一类是注册Bean,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一起,把对象、属性、方法完美组装。
10 Spring AOP
AOP(Aspect Oriented Programming):面向切面编程
以下内容参考:SpringAOP
AOP要做的三件事:
- 在哪里切入,也就是权限校验等非业务操作在哪些业务操作中执行
- 在什么时候切入,是业务代码执行前还是执行后
- 切入后做什么事,比如权限校验、日志的记录
体系梳理为下图:
概念详解:
- PointCut:切点,决定处理如权限校验、日志记录等在何处切入到业务代码中(即织入weaving切面)。分为execution方式和annotation方式。前者可以使用路径表达式指定哪些类织入切面,后者可以指定被哪些注解修饰的代码织入切面
- Advice:处理,包括了处理的时机和处理内容,处理内容就是要做什么事。处理时机就是在什么时机执行处理内容,分为前置处理(即业务代码执行前)、后置处理(业务代码执行后)等
- Aspect:切面,即PonitCut和Advice
- Joint point:连接点,程序执行的一个点。例如,一个方法的执行或者一个异常的处理,在SpringAOP中,一个连接点总是代表一个方法的执行
- Weaving:织入,就是通过动态代理,在目标对象方法中执行处理内容的过程

10.1 动态代理
package com.itheima.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;/*** 模拟一个消费者*/public class Client {public static void main(String[] args) {final Producer producer = new Producer();/*producer.saleProduct(10000f);*//*动态代理:(和装饰者模式的区别)特点:字节码随用随创建,随用随加载作用:不修改源码的基础上,对方法增强分类:1. 基于接口的动态代理2. 基于子类的动态代理基于接口的动态代理:涉及的类:Proxy提供者:JDK官方如何创建代理对象:使用Proxy类中的newProxyInstance方法创建代理对象的要求:被代理类最少实现一个接口,如果没有则不能使用newProxyInstance方法的参数:ClassLoader:类加载器他是用于加载代理对象字节码的,和被代理对象使用相同的类加载器.固定写法Class[]:字节码数组他是用于代理对象和被代理对象有相同的方法。(即继承同一个接口)InvocationHandler:用于提供增强的代码他是让我们写如何代理,我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不必须此接口的实现类,都是谁用谁写*/IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),new InvocationHandler() {/*** 作用:执行被代理对象的任何接口方法都会经过该方法* 方法参数的含义* @param proxy 代理对象的引用* @param method 当前执行的方法* @param args 当前执行方法所需的参数* @return 和被代理对象方法有相同的返回值* @throws Throwable*/@Overridepublic Object invoke(Object proxy, Method method, Object[] args) 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;}});proxyProducer.saleProduct(10000f);}}
10.2 AOP的XML配置
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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--配置spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--spring中基于XML的AOP配置步骤:1. 把通知bean也交给spring来管理2. 使用aop:config标签,表明开始AOP的配置3. 使用aop:aspect标签,表明配置切面id: 属性是给切面一个唯一的标识ref属性:是指定通知类bean的id4. 在aop:aspect标签的内部使用对应的标签来配置通知的类型我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知aop:before: 表示配置前置通知method属性:用于指定Logger类中哪个方法是前置通知 // printLog()pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强5. 切入点表达式的写法:关键字:execution(表达式)表达式:访问修饰符 返回值 包名.包名.包名....类名.方法名(参数列表)标准的表达式写法:public void com.itheima.service.impl.AccountServiceImpl.saveAccount()访问修饰符可以省略void com.itheima.service.impl.AccountServiceImpl.saveAccount()返回值可以使用通配符表示任意返回值* com.itheima.service.impl.AccountServiceImpl.saveAccount()包名可以使用通配符,表示任意包, 但是有几级包, 就需要写几个** *.*.*.*.AccountServiceImpl.saveAccount()包名可以使用..表示当前包及其子包* *..AccountServiceImpl.saveAccount()类名和方法名都可以使用*来实现通配* *..*.*()参数列表:可以直接写数据类型:基本类型直接写名称 int引用类型写包名.类名的方式 java.lang.String可以使用通配符, 表示任意类型, 但是必须有参数可以使用..表示有无参数均可, 有参数可以是任意类型全通配写法:* *..*.*(..)实际开发中, 切入点表达式的通常写法:切到业务层实现类下的所有方法* com.itheima.service.impl.*.*(..)--><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切面--><aop:aspect id="logAdvice" ref="logger"><!--配置通知的类型且建立通知方法和切入点方法的关联--><aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.AccountServiceImpl.saveCount(..))"></aop:before></aop:aspect></aop:config></beans>
main文件
package com.itheima.test;import com.itheima.service.AccountService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 测试AOP的配置*/public class AOPTest {public static void main(String[] args) {//1. 获取容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//2. 获取对象AccountService as = (AccountService) ac.getBean("accountService");//3. 执行方法as.saveAccount(); // 只会在该方法之前执行printLog()方法as.deleteAccount();as.updateAccount(1);}}
环绕通知配置
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--配置spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切入点表达式 id属性:用于指定表达式的唯一标识expression属性:用于指定表达式内容此标签写在aop:aspect标签内部只能当前切面使用它还可以写在aop:aspect外面,此时就变成了所有切面可用, 提升了复用性--><aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/><!--配置切面--><aop:aspect id="logAdvice" ref="logger"><!--前置通知: 在切入点方法执行之前执行<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before><!–后置通知:在切入点方法执行之后执行–><aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning><!–异常通知:在切入点方法执行产生异常之后执行–><aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing><!–最终通知:无论切入点方法是否正常执行它都会在其后边执行–><aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>--><!--配置环绕通知 详细的注释请看Logger类中--><aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around></aop:aspect></aop:config></beans>
code
package com.itheima.utils;import org.aspectj.lang.ProceedingJoinPoint;/*** 用于记录日志的工具类,它里面提供了公共的代码*/public class Logger {/*** 前置通知*/public void beforePrintLog() {System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了");}/*** 后置通知*/public void afterReturningPrintLog() {System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了");}/*** 异常通知*//* public void afterThrowingPrintLog() {System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了");}*//*** 最终通知*/public void afterPrintLog() {System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了");}/*** 环绕通知* 问题:* 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了* 分析:* 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有* 解决:* Spring框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于调用切入点方法* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用** spring中的环绕通知:* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式*/public Object aroundPrintLog(ProceedingJoinPoint pjp) {Object rtValue = null;try {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……前置");//得到方法执行所需的参数Object[] args = pjp.getArgs();//明确调用业务层方法(切入点方法)// System.out.println(args.length);rtValue = pjp.proceed(args);System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……后置");return rtValue;} catch (Throwable throwable) {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……异常");throw new RuntimeException(throwable);} finally {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……最终");}}}
10.3 AOP的注解配置
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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--配置spring创建容器时要扫描的包--><context:component-scan base-package="com.itheima"></context:component-scan><!--配置spring开启注解AOP的支持--><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
Logger
package com.itheima.utils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;/*** 用于记录日志的工具类,它里面提供了公共的代码*/@Component("logger") // 将该类注入到IOC容器中@Aspect //表示当前类是一个切面类public class Logger {@Pointcut("execution(* com.itheima.service.impl.*.*(..))")private void pt1() {};/*** 前置通知*/// @Before("pt1()")public void beforePrintLog() {System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了");}/*** 后置通知*/// @AfterReturning("pt1()")public void afterReturningPrintLog() {System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了");}/*** 异常通知*/// @AfterThrowing("pt1()")public void afterThrowingPrintLog() {System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了");}/*** 最终通知*/// @After("pt1()")public void afterPrintLog() {System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了");}/*** 环绕通知* 问题:* 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了* 分析:* 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有* 解决:* Spring框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于调用切入点方法* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用** spring中的环绕通知:* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式*/@Around(("pt1()"))public Object aroundPrintLog(ProceedingJoinPoint pjp) {Object rtValue = null;try {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……前置");//得到方法执行所需的参数Object[] args = pjp.getArgs();//明确调用业务层方法(切入点方法)rtValue = pjp.proceed(args);System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……后置");return rtValue;} catch (Throwable throwable) {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……异常");throw new RuntimeException(throwable);} finally {System.out.println("Logger类中的aroundPrintLog方法开始记录日志了……最终");}}}
11 Spring中的事务处理
JavaEE进行分层开发,事务处理位于业务层
- Spring框架提供了一组事务控制的接口
- spring的事务控制都是基于AOP的,既可以使用编程的方式实现,也可以使用配置的方式
事务管理主要包括:
- 开启事务:beginTransaction()
- 提交事务:commit(),这时候成功的数据才会序列化到硬盘上,解决多线程操作数据的问题(银行取钱)
- 回滚事务:rollback(),回滚到上次代码没有出错的数据状态
- 释放连接:release(),还回连接池中
11.1 事务的XML配置
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"><!--注入Dao--><property name="accountDao" ref="accountDao"></property><!--注入事务管理器, 事务控制一般是在业务层进行--><property name="txManager" ref="txManager"></property></bean><bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl>"><!--注入QueryRunner--><property name="runner" ref="runner"></property><!--注入ConnectionUtils--><property name="connectionUtils" ref="connectionUtils"></property></bean><!--配置QueryRunner对象--><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean><!--配置数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--连接数据库的必备信息--><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean><!--配置connection的工具类 ConnectionUtils--><bean id="connectionUtils" class="com.itheima.utils.ConnectionUtils"><!--注入数据源--><property name="dataSource" ref="dataSource"></property></bean><!--配置事务管理器--><bean id="txManager" class="com.itheima.utils.TransactionManager"><property name="connectionUtils" ref="connectionUtils"></property></bean><!--配置AOP--><aop:config><!--配置通用切入点表达式--><aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/><aop:aspect id="txAdvice" ref="txManager"><!--配置前置通知:开启事务--><aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before><!--配置后置通知:提交事务--><aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning><!--配置异常通知:回滚事务--><aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing><!--配置最终通知:释放连接--><aop:after method="release" pointcut-ref="pt1"></aop:after></aop:aspect></aop:config>
事务管理类
package com.itheima.utils;import java.sql.SQLException;/*** 和事务管理相关的工具类,它包含了:开启事务,提交事务,回滚事务,和释放连接*/public class TransactionManager {private ConnectionUtils connectionUtils;public void setConnectionUtils(ConnectionUtils connectionUtils) {this.connectionUtils = connectionUtils;}/*** 开启事务*/public void beginTransaction() {try {connectionUtils.getThreadConnection().setAutoCommit(false);} catch (SQLException e) {e.printStackTrace();}}/*** 提交事务*/public void commit() {try {connectionUtils.getThreadConnection().commit();} catch (SQLException e) {e.printStackTrace();}}/*** 回滚事务*/public void rollback() {try {connectionUtils.getThreadConnection().rollback();} catch (SQLException e) {e.printStackTrace();}}/*** 释放连接*/public void release() {try {connectionUtils.getThreadConnection().close(); //还回连接池中connectionUtils.removeConnection();} catch (SQLException e) {e.printStackTrace();}}}
11.2 事务的注解配置
通过使用进程连接点(ProceedingJoinPoint)处理
TransactionManager :都是在 arroundAdvice 中调用其余的方法
package com.itheima.utils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.sql.SQLException;/*** 和事务管理相关的工具类,它包含了:开启事务,提交事务,回滚事务,和释放连接*/@Component("txManager")@Aspectpublic class TransactionManager {@Autowiredprivate ConnectionUtils connectionUtils;@Pointcut("execution(* com.itheima.service.impl.*.*(..))")private void pt1() {}/*** 开启事务*/public void beginTransaction() {try {connectionUtils.getThreadConnection().setAutoCommit(false);} catch (SQLException e) {e.printStackTrace();}}/*** 提交事务*/public void commit() {try {connectionUtils.getThreadConnection().commit();} catch (SQLException e) {e.printStackTrace();}}/*** 回滚事务*/public void rollback() {try {connectionUtils.getThreadConnection().rollback();} catch (SQLException e) {e.printStackTrace();}}/*** 释放连接*/public void release() {try {connectionUtils.getThreadConnection().close(); //还回连接池中connectionUtils.removeConnection();} catch (SQLException e) {e.printStackTrace();}}@Around("pt1()") // 事务的控制是环绕通知public Object arroundAdvice(ProceedingJoinPoint pjp) {Object rtValue = null;try{//1. 获取参数Object[] args = pjp.getArgs();//2. 开启事务this.beginTransaction();//3. 执行方法rtValue = pjp.proceed(args);//4. 提交事务this.commit();//返回结果return rtValue;} catch (Throwable e) {//5. 回滚事务this.rollback();throw new RuntimeException(e);} finally {//6. 释放资源this.release();}}}
12 SpringJdbc
一般配置数据源的方式
public static void main(String[] args) {//准备数据源,spring的内置数据源DriverManagerDataSource ds = new DriverManagerDataSource();ds.setDriverClassName("com.mysql.jdbc.Driver");ds.setUrl("jdbc:mysql://localhost:3306/eesy");ds.setUsername("root");ds.setPassword("root");//1. 创建对象JdbcTemplate jt = new JdbcTemplate();//给jt设置数据源jt.setDataSource(ds);//2. 执行操作jt.execute("insert into account(name ,money) values('ccc', 1000)");}
使用注解配置,通过反射获得
<!--配置业务层--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!--配置账户的持久层--><bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"><!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>--><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="root"></property></bean>
/*** JdbcTemplate的最基本用法CRUD*/public class JdbcTemplateDemo3 {public static void main(String[] args) {//1. 获取容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//2. 获取对象JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);//3. 执行操作//保存jt.update("insert into account(name, money) values(?, ?)", "eee", 333f);//更新jt.update("update account set name = ?, money = ? where id = ? ", "test", 4567, 1);//删除jt.update("delete from account where id = ?", 2);//查询所有// List<Account> accounts = jt.query("select * from account where money ? ?", new AccountRowMapper(), 1000f);// List<Account> accounts = jt.query("select * from account where money > ?", new BeanPropertyRowMapper<Account>(Account.class), 1000f);// for (Account account : accounts) {// System.out.println(account);// }//查询一个/* List<Account> accounts= jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);//这波操作有点6System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));*///查询返回一行一列(使用聚合函数,但是不含Group by子句)Long count = jt.queryForObject("select count(*) from account where money > ?", Long.class, 1000f);System.out.println(count);}/*** 定义Account的封装策略*/static class AccountRowMapper implements RowMapper<Account> {/*** 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中* @param resultSet* @param i* @return* @throws SQLException*/public Account mapRow(ResultSet resultSet, int i) throws SQLException {Account account = new Account();account.setId(resultSet.getInt("id"));account.setName(resultSet.getString("name"));account.setMoney(resultSet.getFloat("money"));return account;}}}
13 完整的一个Spring的XML配置
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--配置业务层--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!--配置账户的持久层--><bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"><!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>--><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="root"></property></bean><!--spring中基于xml的声明式事务控制配置步骤:1. 配置事务管理器2. 配置事务通知此时我们要导入事务的约束 tx名称空间和约束,同时也需要aop的使用tx:advice标签配置事务通知属性:id:给事务通知起一个唯一标识transaction-manager:给事务通知提供一个事务管理器引用3. 配置AOP中的通用切入点表达式4. 建立事务通知和切入点表达式的对应关系5. 配置事务的属性是在事务的通知tx:advice标签的内部--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--配置事务的通知--><tx:advice id="txAdvice" transaction-manager="transactionManager"><!--配置事务的属性isolation: 用于指定事务的隔离级别,默认值式DEFAULT,propagation:用于指定事务的传播行为。默认值式REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTSread-only:用于指定事务是否只读,只有查询方法才能设置为true,默认值式false,表示读写timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,当产生其他异常时事务回滚,没有默认值,表示任何异常都回滚--><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><!--配置aop--><aop:config><!--配置切入点表达式--><aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut><!--建立切入点表达式和事务通知的对应关系--><aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor></aop:config></beans>
