本文已参与「新人创作礼」活动,一起开启掘金创作之路。
第二章 Spring
2.1、概述
Spring是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以IOC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层Spring MVC 和 持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE企业应用开源框架
2.2、spring的优势
方便解耦,简化开发
通过Spring提供的IoC容器,可以将对象间的依赖关系交由Spring进行控制,避免硬编码所造成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用
AOP编程的支持
通过Spring的AOP功能,方便进行面向切面的编程,许多不容易用传统OOP实现的功能可以通过AOP轻松应付
声明式事务的支持
可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活地进行事务的管理,提高开发效率和质量
方便程序的测试
可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情
方便集成各种优秀框架
Spring 可以降低各种框架的使用难度,提供了对各种优秀框架(Struts、Hibernate、Hessian、Quartz等)的直接支持
降低 JavaEE API 的使用难度
Spring 对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些API的使用难度大为降低
Java源码是经典学习范例
Spring 的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对 Java 设计模式灵活运用以及对 Java 技术的高深造诣。它的源代码无疑是 Java 技术的最佳实践的范例。
2.3、spring的体系结构
2.4、程序的耦合
耦合:程序间的依赖关系
包括:类之间的依赖
方法间的依赖
解耦:降低程序间的依赖关系
实际开发中:应该做到编译期不依赖,运行时才依赖
解耦的思路:
第一步:使用反射来创建对象,而避免使用new关键字
第二步:通过读取配置文件来获取要创建的对象全限定类名
public class JdbcDemo01 {
public static void main(String[] args) throws Exception {
//1.注册驱动
//此处使用new方法时,若项目中没有导入mysqlJdbc数据包,则编译时就报错,此时称之为编译时依赖jar包
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//使用以下方式时,若没有导入jar包,则运行时才会报错,此时叫出现异常,运行时依赖jar包,当然,如果要使用其他类型数据库时,需要修改源码,因此最好使用配置文件来读取对象的全限定类名
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy", "root", "123456");
//3.获取操作数据库的预处理对象
PreparedStatement pstm = conn.prepareStatement("select * from account");
//4.执行SQL,获取结果集
ResultSet resultSet = pstm.executeQuery();
//5.遍历结果集
while (resultSet.next()){
System.out.println(resultSet.getString("name"));
}
//6.释放资源
resultSet.close();
pstm.close();
conn.close();
}
}
2.4.1、工厂模式解耦
bean.properties
accountService=com.ywb.service.impl.AccountServiceImpl
accountDao=com.ywb.dao.impl.AccountDaoImpl
BeanFactory
/**
* @author yang
* @date 2021年07月23日 20:09
* 一个创建Bean对象的工厂
*
* Bean:在计算机用语中,有可重用组件的含义
* JavaBean:用java语言编写的可重用组件
* javaBean > 实体类
*
* 它就是创建我们的service和dao对象的
* 第一步:需要一个配置文件来配置我们的service和dao
* 配置的内容:唯一标识=全限定类名(key=value)
* 配置文件可以是xml或者properties
* 第二步:通过读取配置文件中配置的内容,反射创建对象
*/
public class BeanFactory {
//定义一个properties对象
private static Properties props;
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对象
* @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;
}
}
使用:
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
private AccountServiceImpl as = (AccountServiceImpl) BeanFactory.getBean("accountService");
分析:使用以上方法时,每次使用getBean方法都实例化一次对象,每次都是新的对象,为多例模式
改造:使用Map集合存储对象,只创建一次对象,创建后放在集合中,需要用的时候取出即可
/**
* @author yang
* @date 2021年07月23日 20:09
* 一个创建Bean对象的工厂
*
* Bean:在计算机用语中,有可重用组件的含义
* JavaBean:用java语言编写的可重用组件
* javaBean > 实体类
*
* 它就是创建我们的service和dao对象的
* 第一步:需要一个配置文件来配置我们的service和dao
* 配置的内容:唯一标识=全限定类名(key=value)
* 配置文件可以是xml或者properties
* 第二步:通过读取配置文件中配置的内容,反射创建对象
*/
public class BeanFactory {
/**
* 定义一个properties对象
*/
private static Properties props;
/**
* 定义一个容器,存放bean对象
*/
private static Map<String,Object> beans;
static {
try{
//实例化对象
props = new Properties();
//获取properties的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration<Object> keys = props.keys();
//遍历keys
while (keys.hasMoreElements()){
//取出每个key
String key = keys.nextElement().toString();
//根据key获取全限定类名
String beanPath = props.getProperty(key);
//通过反射创建对象
Object value = Class.forName(beanPath).newInstance();
//将key和value储存进map集合
beans.put(key,value);
}
}catch (Exception e){
throw new ExceptionInInitializerError("初始化properties失败");
}
}
/**
* 根据bean的名称来获取bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
2.5、Spring基于XML的ioc环境搭建和入门
控制反转:把创建对象的权利交给框架,是框架的重要特征,并非面向对象编程的专用术语。它包括依赖注入和依赖查找
作用:削减计算机程序的耦合
环境搭建:
导入jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ywb</groupId>
<artifactId>day01_eesy_03spring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
</dependencies>
</project>
配置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">
<!--把对象的创建交给spring来管理-->
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.ywb.dao.impl.AccountDaoImpl"></bean>
</beans>
使用:
public class Client {
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
//方式一:强转类型
IAccountService accountService = (IAccountService) ac.getBean("accountService");
//方式二:传入对应类型的字节码
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(accountService);
System.out.println(accountDao);
}
}
ApplicationContext的三个常用实现类:
- ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了
- FileSystemXmlApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)
- AnnotationConfigApplicationContext:用于读取注解创建容器的
核心容器的两个接口引发出的两个问题:
ApplicationContext:它在构建核心容器时,创建对象采取的思想是采用立即加载的方式,只要一读取完配置文件,马上就创建配置文件中配置的对象(单例对象适用)(通常使用这个)
BeanFactory:它在构建核心容器时,创建对象采取的思想是采用延迟加载的方式,什么时候根据id获取对象了,什么时候才真正地创建对象(多例对象适用)
三种创建bean对象的方式:
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">
<!--把对象的创建交给spring来管理-->
<!--spring对bean的管理细节
1.创建bean的三种方式
2.bean对象的作用范围
3.bean对象的生命周期
-->
<!--创建bean的三种方式-->
<!--第一种方式:使用默认构造函数创建。
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建
name标签为别名,可取多个
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl" name="a1,a2..."></bean>
-->
<!--第二种方式:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
<bean id="instanceFactory" class="com.ywb.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
-->
<!--第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)-->
<bean id="accountService" class="com.ywb.factory.StaticFactory" factory-method="getAccountService"></bean>
</beans>
对应第二种方式:
看成是jar包中的类
/**
* @author yang
* @date 2021年07月25日 1:02
* 模拟一个工厂类(该类可能是存在与jar包中的,我们无法通过修改源代码的方式来提供默认构造函数)
*/
public class InstanceFactory {
public IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
对应第三种方式:
对应jar包中的类
/**
* @author yang
* @date 2021年07月25日 1:02
* 模拟一个工厂类(该类可能是存在与jar包中的,我们无法通过修改源代码的方式来提供默认构造函数)
*/
public class StaticFactory {
public static IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
2.6、bean的作用范围和生命周期
bean标签的scope属性:用于指定bean的作用范围
取值:singleton:单例的(默认)
prototype:多例的
request:作用于web应用的请求范围
session:作用于web应用的会话范围
global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
常用:单例或多例
bean对象的生命周期
单例对象
出生:当容器创建时对象出生
活着:只要容器还在,对象一直活着
死亡:容器销毁,对象消亡
总结:单例对象的生命周期和容器相同
多例对象
出生:当我们使用对象时spring框架为我们创建
活着:对象只要是在使用过程中就一直活着
死亡:当对象长时间不用,且没有别的对象引用时,由java的垃圾回收机制回收
2.7、spring的依赖注入
依赖注入: Dependency Injection
IOC的作用: 降低程序间的耦合(依赖关系)
依赖关系的管理:
- 以后都交给spring来维护
- 在当前类需要使用到其他类的对象时,由spring来提供,我们只需要在配置文件中说明
依赖关系的维护:称之为依赖注入
依赖注入: 能注入的数据有三类: 基本类型和String 其他bean类型(在配置文件中或者注解中配置过的bean) 复杂类型/集合类型 注入的方式三种: 第一种:使用构造函数提供 第二种:使用set方法提供 第三种:使用注解提供
构造函数注入: 使用的标签:constructor-arg 标签出现的位置:bean标签的内部 标签的属性: type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型 index:用于指定要注入的数据给构造函数中指定索引位置的函数赋值。索引的位置从0开始 name:用于指定给构造函数中指定名称的参数赋值(常用) ====================以上三个用于指定给构造函数中哪个参数赋值===================== value:用于提供基本类型数据和String类型的数据 ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象 优势: 在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功 弊端: 改变了这个bean对象的实例化方式,使我们在创建对象时如果用不到这些数据也必须提供
set方法注入(常用) 涉及的标签:property 出现的位置:bean标签的内部 标签的属性: name:用于指定时所调用的set方法名称 value:用于提供基本类型数据和String类型的数据 ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象 优势: 创建对象时没有明确的限制,可以直接使用默认构造函数 弊端: 如果有某个成员必须有值,则获取对象时有可能set方法没有执行
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">
<!--spring中的依赖注入
依赖注入:
Dependency Injection
IOC的作用:
降低程序间的耦合(依赖关系)
依赖关系的管理:
以后都交给spring来维护
在当前类需要使用到其他类的对象时,由spring来提供,我们只需要在配置文件中说明
依赖关系的维护:
称之为依赖注入
依赖注入:
能注入的数据有三类:
基本类型和String
其他bean类型(在配置文件中或者注解中配置过的bean)
复杂类型/集合类型
注入的方式三种:
第一种:使用构造函数提供
第二种:使用set方法提供
第三种:使用注解提供
-->
<!--构造函数注入:
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签的属性:
type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
index:用于指定要注入的数据给构造函数中指定索引位置的函数赋值。索引的位置从0开始
name:用于指定给构造函数中指定名称的参数赋值(常用)
====================以上三个用于指定给构造函数中哪个参数赋值=====================
value:用于提供基本类型数据和String类型的数据
ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
优势:
在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功
弊端:
改变了这个bean对象的实例化方式,使我们在创建对象时如果用不到这些数据也必须提供
-->
<bean id="accountService" class="com.ywb.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方法注入(常用)
涉及的标签:property
出现的位置:bean标签的内部
标签的属性:
name:用于指定时所调用的set方法名称
value:用于提供基本类型数据和String类型的数据
ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
优势:
创建对象时没有明确的限制,可以直接使用默认构造函数
弊端:
如果有某个成员必须有值,则获取对象时有可能set方法没有执行
-->
<bean id="accountService2" class="com.ywb.service.impl.AccountServiceImpl2">
<property name="name" value="test"></property>
<property name="age" value="19"></property>
<property name="birthday" ref="now"></property>
</bean>
<!--复杂类型的注入/集合类型的注入
用于给list结构集合注入的标签:
list array set
用于给map结构集合注入的标签:
map props
结构相同,标签可以互换
-->
<bean id="accountService3" class="com.ywb.service.impl.AccountServiceImpl3">
<property name="myStr">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<property name="myList">
<list>
<value>CCC</value>
<value>DDD</value>
<value>EEE</value>
</list>
</property>
<property name="mySet">
<set>
<value>FFF</value>
<value>GGG</value>
<value>HHH</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>
</beans>
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("IAccountService中的方法执行。。。"+"--"+name+"--"+age+"--"+birthday);
}
}
public class AccountServiceImpl2 implements IAccountService {
private String name;
private Integer age;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void saveAccount() {
System.out.println("IAccountService中的方法执行。。。"+"--"+name+"--"+age+"--"+birthday);
}
}
public class AccountServiceImpl3 implements IAccountService {
private String[] myStr;
private List<String> myList;
private Set<String> mySet;
private Map<String,String> myMap;
private Properties myProps;
public void setMyStr(String[] myStr) {
this.myStr = myStr;
}
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;
}
public void saveAccount() {
System.out.println(Arrays.toString(myStr));
System.out.println(myList);
System.out.println(mySet);
System.out.println(myMap);
System.out.println(myProps);
}
}
2.8、spring基于注解的开发
bean.xml的配置
<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.ywb"></context:component-scan>
</beans>
用于创建对象的注解
-
作用与在xml配置文件中编写一个标签的作用是一样的
-
Component:
- 作用:用于把当前类对象存入spring容器中
- 属性:value用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母小写
-
Controller:一般用在表现层
-
Service:一般用在业务层
-
Repository:一般用在持久层
以上三个注解的作用和属性与Component是一模一样的
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao1;
public void saveAccount() {
accountDao1.saveAccount();
}
}
用于注入数据的
-
作用与在xml配置文件中的bean标签写一个标签一样
-
Autowired:
-
参数:@Autowired(required = false) 表示这个对象可以为空
- 作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
- 如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错
- 如果ioc容器中有多个类型匹配时,用变量名和id进行匹配,若没有匹配到则报错
- 出现位置:可以是变量上,也可以是方法上
- 细节:在使用注解注入时,set方法就不是必须的了
-
Qualifier(给在成员属性注解时需要和Autowired一起使用):
- 作用:在按照类型注入基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以单独使用
- 属性:value用于指定注入bean的id
public class AccountServiceImpl implements IAccountService {
@Autowired
@Qualifier("accountDao")
private IAccountDao accountDao2;
public void saveAccount() {
accountDao2.saveAccount();
}
}
public QueryRunner createQueryRunner(@Qualifier("dataSource1") DataSource dataSource){
return new QueryRunner(dataSource);
}
-
Resource:
- 作用:直接按照bean的id注入。它可以独立使用
-
默认通过byname的方式注入,如果找不到名字,就通过byType的方式
-
属性:name:用于指定name的id
以上三个注解都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
-
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao accountDao2;
public void saveAccount() {
accountDao2.saveAccount();
}
}
注意:集合类型的注入只能通过xml来实现
-
Value
- 作用:用于注入基本类型和String类型的数据
- 属性:value:用于指定数据的值。它可以使用spring中的SpEL(也就是spring的el表达式)
- SpEL的写法:${表达式}
用于改变作用范围的
-
作用和在bean标签中使用scope属性实现的功能是一样的
-
Scope:
- 作用:用于指定bean的作用范围
- 属性:value:指定范围的取值。常用值:singleton单例 prototype多例
和生命周期相关的(了解)
-
作用和在bean标签中使用init-method和destroy-method的作用是一样的
-
preDestroy
- 作用:用于指定销毁方法
-
postConstruct
- 作用:用于指定初始化方法
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao accountDao2;
public void saveAccount() {
accountDao2.saveAccount();
}
@PostConstruct
public void init() {
System.out.println("初始化完成");
}
@PreDestroy
public void destroy() {
System.out.println("销毁完成");
}
}
public class Client {
/**
* 获取spring的IOC容器,并根据id获取对象
*
* @param args
*/
public static void main(String[] args) {
//1.获取核心容器对象
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService accountService2 = (IAccountService) ac.getBean("accountService");
System.out.println(accountService2);
accountService2.saveAccount();
ac.close();
}
}
/*
结果:
初始化完成
com.ywb.service.impl.AccountServiceImpl@43d7741f
保存了账户
销毁完成
*/
2.9、使用注解代替xml文件(难点,纯Java配置方式)
spring中的新注解
-
Configuration
- 作用:指定当前类是一个配置类
-
ComponentScan
-
作用:用于通过注解指定spring在创建容器时需要扫描的包
-
细节:当该类作为AnnotationConfigApplicationContext对象的创建参数时,可以不写
-
属性:
-
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
- 我们使用此注解就等同于在xml中配置了:
-
<context:component-scan base-package="com.ywb"></context:component-scan>
-
-
-
Bean
-
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
-
属性:
- name:用于指定bean的id。当不写时,默认值是当前方法的名称
-
细节
- 当我们用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
- 查找的方式和Autowired注释的作用是一样的
-
-
Import
-
作用:用于导入其他的配置类
-
属性:
- value:用于指定其他配置类的字节码
-
当我们使用Import注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
-
-
PropertySource
- 作用:用于指定properties文件的位置
- 属性:value:指定文件的名称和路径。
- 关键字:classpath:表示类路径下
//指定当前类是一个配置类
@Configuration
//指定spring在创建容器时需要扫描的包
@ComponentScan(basePackages = "com.ywb")
//导入其他的配置类
@Import(JdbcConfig.class)
//指定properties文件的位置
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@Value("jdbc.driver")
private String driver;
@Value("jdbc.url")
private String url;
@Value("jdbc.username")
private String username;
@Value("jdbc.password")
private String password;
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean("dataSource")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUser("root");
ds.setPassword("123456");
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
测试类(使用AnnotationConfigApplicationContext):
public void testFindAll(){
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.获取对象
IAccountService accountService = (IAccountService) ac.getBean("accountService");
//3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
2.10、Spring整合junit
spring整合junit的配置
-
导入spring整合junit的jar(坐标)
-
使用Junit提供的一个注解(@Runwith)把原有的main方法替换了,替换成spring提供的
-
告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在的位置
当我们使用spring 5.x版本的时候,要求junit的jar包版本是4.1.2及以上
注解类使用示例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService accountService;
@Test
public void testFindAll(){
//3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
}
xml文件使用示例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService accountService;
@Test
public void testFindAll(){
//3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
}
2.11、转账事务问题解决
ConnectionUtils类:
/**
* @author yang
* @date 2021年08月01日 1:20
* 连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public Connection getThreadConnection(){
try {
//1.先从ThreadLocal上获取
Connection conn = tl.get();
//2.判断conn是否为空
if (conn==null){
//3.从数据源中获取
conn = dataSource.getConnection();
tl.set(conn);
}
//4.返回当前线程绑定的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
TransactionManager类:
/**
* @author yang
* @date 2021年08月01日 1:31
* 和事务管理相关的工具类:开启事务,提交事务,回滚事务,释放连接
*/
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try{
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try{
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try{
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try{
//还回池中
connectionUtils.getThreadConnection().close();
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
}
AccountDaoImpl类:
/**
* @author yang
* @date 2021年07月29日 21:37
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e){
throw new RuntimeException(e);
}
}
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ?",new BeanListHandler<Account>(Account.class),accountName);
if (accounts==null || accounts.size()==0){
return null;
}
if (accounts.size() > 1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
AccountServiceImpl类:
/**
* @author yang
* @date 2021年07月29日 21:32
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
private TransactionManager transactionManager;
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void transfer(String sourceName, String targetName, Float money) {
try{
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
//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);
//3.提交事务
transactionManager.commit();
}catch (Exception e){
//5.回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
transactionManager.release();
}
}
}
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">
<!--配置Service-->
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="com.ywb.dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
<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="123456"></property>
</bean>
<!--配置ConnectionUtils-->
<bean id="connectionUtils" class="com.ywb.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager" class="com.ywb.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>
2.12、动态代理回顾
基于接口的动态代理
-
动态代理:
-
特点:字节码随用随创建,随用随加载
-
作用:不修改源码的基础上对方法进行增强
-
分类:
- 基于接口的动态代理
- 基于子类的动态代理
- 基于接口的动态代理:
-
涉及的类:Proxy
-
提供者:JDK官方
-
-
如何创建代理对象:
- 使用Proxy类中的newProxyInstance方法
-
创建代理对象的要求:
- 被代理类最少实现一个接口,如果没有则不能使用
-
newProxyInstance方法的参数:
-
ClassLoader:类加载器
- 它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。(固定写法)
-
Class[]:字节码数组
- 它是用于让代理对象和被代理对象有相同的方法。(固定写法)
-
InvocationHandler:用于提供增强的代码
- 它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的
- 此接口的实现类都是谁用谁写
-
接口类:
/**
* @author yang
* @date 2021年08月01日 15:13
*/
public interface IProducer {
/**
* 销售
* @param money
*/
public void saleProduct(Float money);
/**
* 售后
* @param money
*/
public void afterService(Float money);
}
实现类
/**
* @author yang
* @date 2021年08月01日 15:09
* 一个生产者
*/
public class Producer implements IProducer{
/**
* 销售
* @param money
*/
public void saleProduct(Float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 售后
* @param money
*/
public void afterService(Float money){
System.out.println("提供售后服务,并拿到钱:"+money);
}
}
动态代理
/**
* @author yang
* @date 2021年08月01日 15:16
* 模拟一个消费者
*/
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(Producer.class.getClassLoader(), Producer.class.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);
}
return returnValue;
}
});
proxyProducer.saleProduct(1000f);
}
}
基于子类的动态代理
public class Producer{
/**
* 销售
* @param money
*/
public void saleProduct(Float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 售后
* @param money
*/
public void afterService(Float money){
System.out.println("提供售后服务,并拿到钱:"+money);
}
}
/**
* @author yang
* @date 2021年08月01日 15:16
* 模拟一个消费者
*/
public class Client {
public static void main(String[] args) {
/**
* 动态代理:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法进行增强
* 分类:
* 基于接口的动态代理
* 基于子类的动态代理
* 基于子类的动态代理:
* 涉及的类:Enhancer
* 提供者:第三方cglib库
* 如何创建代理对象:
* 使用Enhancer类中的create方法
* 创建代理对象的要求:
* 被代理类不能是最终类
* create方法的参数:
* Class:字节码
* 它是用于指定被代理对象的字节码
* Callback:用于提供增强的代码
* 它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的
* 此接口的实现类都是谁用谁写
* 我们一般写的都是该接口的子接口实现类:MethodInterceptor
*/
final Producer producer = new Producer();
Producer cglibProducer = (Producer) Enhancer.create(Producer.class, new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//获取参数
Float money = (Float)objects[0];
if ("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
}
});
cglibProducer.saleProduct(1000f);
}
}
2.13、使用动态代理实现事务控制
BeanFactory:
/**
* @author yang
* @date 2021年08月02日 15:54
*/
public class BeanFactory {
@Autowired
private IAccountService accountService;
@Autowired
private TransactionManager transactionManager;
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public final void setAccountService(AccountServiceImpl accountService) {
this.accountService = accountService;
}
public IAccountService getAccountService(){
return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
try{
//1.开启事务
transactionManager.beginTransaction();
System.out.println("执行了开启事务");
//2.执行操作
System.out.println("即将执行invoke方法");
returnValue = method.invoke(accountService, args);
System.out.println("执行了invoke方法");
//3.提交事务
transactionManager.commit();
System.out.println("执行了事务提交方法");
//4.返回结果
System.out.println("返回结果");
return returnValue;
}catch (Exception e){
//5.回滚事务
System.out.println("回滚事务");
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
System.out.println("释放连接");
transactionManager.release();
}
}
});
}
}
AccountServiceImpl:
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("转账开始");
//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);
System.out.println("转帐结束");
}
bean.xml(重点:配置代理的Service类)
<?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">
<!--配置代理的AccountService-->
<bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService">
</bean>
<!--配置BeanFactory-->
<bean id="beanFactory" class="com.ywb.factory.BeanFactory">
<property name="accountService" ref="accountService"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!--配置Service-->
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="com.ywb.dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
<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="123456"></property>
</bean>
<!--配置ConnectionUtils-->
<bean id="connectionUtils" class="com.ywb.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager" class="com.ywb.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>
2.14、AOP
-
含义
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
-
作用及优势
在程序运行期间,不修改源码对已有方法的增强
减少重复代码
提高开发效率
维护方便
-
实现方式:使用动态代理
-
AOP相关术语:
-
Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
-
Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义(被增强的)所有的切入点都是连接点,反之不然
-
Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知
-
Introduction(引介):引介是一种特殊的通知,在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或Field
-
Target(目标对象):代理的目标对象(被代理对象)
-
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程
spring采用动态代理织入,而AspectJ采用编译器织入和类装载期织入
-
Proxy(代理):一个类被AOP织入增强后,就产生了一个结果代理类
-
Aspect(切面):是切入点和通知(引介)的结合
-
2.15、spring基于XML的AOP
spring中基于xml的AOP配置方式
- 把通知bean也交给spring管理
- 使用aop:config标签表明开始AOP的配置
- 使用aop:aspect标签表明配置切面 id属性:给切面提供一个唯一标识 ref属性:是指定通知类bean的id
- 在aop:aspect标签的内部使用对应的标签来配置通知的类型 我们现在示例的是让printLog方法在切入点方法执行之前执行,为前置通知 aop:before:表示配置前置通知 method属性:用于指定Logger类中哪个方法是前置通知 pointcut属性:用于指定切入点表达式,该表达式含义指的是对业务层哪些方法增强
导包:aspectjweaver
切入表达式的写法;
关键字:execution(表达式)
表达式:
访问修饰符 返回值 全限定类名.方法名(参数列表)
标准的表达式写法:
public void com.ywb.service.impl.AccountServiceImpl.saveAccount()
访问修饰符可以省略
void com.ywb.service.impl.AccountServiceImpl.saveAccount()
返回值可以使用通配符,表示任何返回值
* com.ywb.service.impl.AccountServiceImpl.saveAccount()
包名可以使用通配符,表示任意包。但是有几级包就需要写几个*.
* *.*.*.*.AccountServiceImpl.saveAccount()
包名可以使用..表示当前包及其子包
* *..AccountServiceImpl.saveAccount()
类名和方法名都可以使用*来实现通配
* *..*.saveAccount()
* *..*.*()
参数列表:
可以直接写数据类型:
基本类型直接写名称 int
引用类型写包名.类名的方式 java.lang.String
可以使用通配符表示任意类型,但必须有参数
可以使用..表示有无参数均可,有参数可以是任意类型
* *..*.*(..)
全通配写法;
* *..*.*(..)
实际开发中切入点表达式的通常写法:
切到业务层实现类下的所有方法
* com.ywb.service.impl.*.*(..)
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/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 definitions here -->
<!--配置spring的ioc-->
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl"></bean>
<!--配置Logger类-->
<bean id="logger" class="com.ywb.utils.Logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(public void com.ywb.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
</aop:aspect>
</aop:config>
</beans>
五种通知方式的配置
<?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 definitions here -->
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl"></bean>
<bean id="logger" class="com.ywb.utils.Logger"></bean>
<aop:config>
<!--配置切入点表达式 id属性用于指定表达式的唯一标识 expression用于指定表达式内容
此标签写在aop:aspect标签内部只能当前切面使用
它还可以写在aop:aspect外面,此时就变成了所有切面可用(此时必须写在切面之前)
-->
<aop:pointcut id="pt1" expression="execution(* com.ywb.service.impl.*.*(..))"></aop:pointcut>
<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>
<!--配置环绕通知-->
<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
</beans>
Logger类:
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 pjd){
Object returnValue;
try {
//得到方法执行所需的参数
Object[] args = pjd.getArgs();
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。前置");
//明确调用切入点方法
returnValue = pjd.proceed(args);
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。后置");
return returnValue;
}catch (Throwable t){
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。最终");
}
}
}
环绕通知:
-
问题:当我们配置了环绕通知后,切入点方法没有执行,而通知方法执行了
-
分析:通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用
-
解决:
- spring框架为我们提供了一个接口:ProceedingJoinPoint 该接口有一个方法proceed(),就相当于明确调用切入点方法
- 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
-
spring中的环绕通知:它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
2.16、spring基于注解的AOP
bean.xml文件
配置spring创建容器时要扫描的包
配置spring开启注解aop的支持
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.ywb"></context:component-scan>
<!--配置spring开启注解aop的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
切面类Logger类:
/**
* @author yang
* @date 2021年08月04日 21:56
* 用于记录日志的工具类,提供了公共的代码
*/
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.ywb.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方法开始记录日志了。。。");
}
/**
* 环绕通知
*/
//@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjd){
Object returnValue;
try {
//得到方法执行所需的参数
Object[] args = pjd.getArgs();
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。前置");
//明确调用切入点方法
returnValue = pjd.proceed(args);
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。后置");
return returnValue;
}catch (Throwable t){
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("环绕通知Logger类中的aroundPrintLog方法开始记录日志了。。。最终");
}
}
}
tips:分开使用四种通知的注解时,最终通知会比异常通知和后置通知先执行
使用环绕通知则不会
2.17、spring中的JdbcTemplate
JdbcTemplate概述
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。
-
操作关系型数据的:
JdbcTemplate
HibernateTemplate
-
操作 nosql 数据库的:
RedisTemplate
-
操作消息队列的:
JmsTemplate
我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)
JdbcTemplate作用
用于和数据库交互,实现对表的CRUD操作
最基本的用法
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUsername("root");
ds.setPassword("123456");
//1.创建JdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate();
//2.给jt设置数据源
jt.setDataSource(ds);
//3.执行操作
jt.execute("insert into account(`name`,`money`)values('ddd',1000)");
}
}
使用ioc配置
/**
* @author yang
* @date 2021年08月05日 21:03
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
//保存
jdbcTemplate.update("insert into account(name,money) values(?,?)","fff",1000f);
//更新
jdbcTemplate.update("update account set name=?,money=? where id=?","aaa",1000f,1);
//删除
jdbcTemplate.update("delete from account where id = ?",7);
//查询所有
//写法一
List<Account> accountList = jdbcTemplate.query("select * from account where money>?", new AccountRowMapper(), 900f);
//写法二
List<Account> accountList = jdbcTemplate.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class), 900f);
for (Account account : accountList) {
System.out.println(account);
}
//查询一个
List<Account> accountList = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), 1);
System.out.println(accountList.isEmpty()?"查不到结果":accountList.get(0));
//查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jdbcTemplate.queryForObject("select count(*) from account where money>?", Long.class, 900f);
System.out.println(count);
}
}
/**
* 定义Account的封装策略
*/
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.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
业务实例运用
/**
* @author yang
* @date 2021年08月05日 23:05
*/
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Account findById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
if (accounts.isEmpty()){
return null;
}
return accounts.get(0);
}
public Account findByName(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());
}
}
测试类
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取对象
IAccountDao accountDao = (IAccountDao) ac.getBean("accountDao");
Account account = accountDao.findById(1);
System.out.println(account);
account.setMoney(900f);
accountDao.updateAccount(account);
}
}
配置类
<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="accountDao" class="com.ywb.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<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="123456"></property>
</bean>
</beans>
JdbcDaoSupport 的使用
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
if (accounts.isEmpty()){
return null;
}
return accounts.get(0);
}
public Account findByName(String accountName) {
List<Account> accounts = super.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) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
2.18、spring声明式事务控制
- JavaEE体系进行分层开发,事务处理位于业务层,spring提供了分层设计业务层的事务处理解决方案
- spring框架为我们提供了一组事务控制的接口。这组接口是在spring-tx-5.0.2RELEASE.jar中
- spring的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。
spring中基于xml的声明式事务控制配置步骤:
-
配置事务管理器
-
配置事务的通知
需要导入事务的约束 tx名称空间和约束,同时也需要aop的
使用tx:advice标签配置事务通知
属性:id:给事务通知起一个唯一标志
transaction-manager:给事务通知提供一个事务管理器引用
-
配置aop中的通用切入点表达式
-
建立事务通知和切入点表达式的对应关系
-
配置事务的属性
是在事务的通知tx:advice标签的内部
isolation:用于指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别
propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
read-only:用于指定事务是否可读。只有查询方法才能设置为true,默认值是false,表示读写
timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位
rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值,表示任何异常都回滚
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">
<bean id="accountDao" class="com.ywb.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="datasource"></property>
</bean>
<bean id="accountService" class="com.ywb.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></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="123456"></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,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
read-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.ywb.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
AccountDaoImpl类:
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
if (accounts.isEmpty()){
return null;
}
return accounts.get(0);
}
public Account findByName(String accountName) {
List<Account> accounts = super.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) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
spring中基于注解的声明式事务控制配置步骤:
- 配置事务管理器
- 开启spring对注解事务的支持
- 在需要事务支持的地方使用@Transactional注解
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.ywb"></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="123456"></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>
AccountDaoImpl类:
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Account findById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
if (accounts.isEmpty()){
return null;
}
return accounts.get(0);
}
public Account findByName(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());
}
}
需要事务控制的类AccountServiceImpl
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true) 只读配置
@Transactional(propagation = Propagation.REQUIRED,readOnly = false) 读写配置
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读配置
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public Account findAccountById(Integer accountId) {
return accountDao.findById(accountId);
}
//配置读写
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void transfer(String sourceName, String targetName, Float money) {
Account source = accountDao.findByName(sourceName);
Account target = accountDao.findByName(targetName);
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
accountDao.updateAccount(source);
//int i = 1/0;
accountDao.updateAccount(target);
}
}
spring中基于纯注解的声明式事务控制:
SpringConfiguration类
/**
* @author yang
* @date 2021年08月07日 17:22
* spring的配置类,相当于bean.xml
*/
@Configuration
@ComponentScan("com.ywb")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}
JdbcConfig类
/**
* @author yang
* @date 2021年08月07日 17:24
* 和连接数据库相关的配置类
*/
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对象
* @param dataSource
* @return
*/
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name = "datasource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
TransactionManager类
/**
* @author yang
* @date 2021年08月07日 18:20
* 和事务相关的配置类
*/
public class TransactionConfig {
/**
* 用于创建事务管理器对象
* @param dataSource
* @return
*/
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}