Spring学习
Spring是什么
Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control: 反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多 著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架。
Spring的优势
方便解耦,简化开发
AOP编程的支持
声明式事务的支持
方便程序的测试
方便集成各种优秀框架
降低JavaEE API的使用难度
Java 源码是经典学习范例
SPRING 的体系结构
基于XML的配置
1、导入相关的jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
2、创建dao和Service
//接口
public interface IAccountDao {
void saveAccout();
}
---------------------------------
//实现类
public class AccountDaoImpl implements IAccountDao {
public void saveAccout() {
System.out.println("保存了账户!");
}
}
//接口
public interface IAccountService {
void saveAccount();
}
---------------------------------
//实现类
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccout();
}
}
3、在resources目录下创建一个任意名称的.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="org.example.service.impl.AccountServiceImpl"></bean>
<!--配置Dao-->
<bean id="accountDao" class="org.example.dao.impl.AccountDaoImpl"></bean>
</beans>
4、测试
public class App {
public static void main( String[] args ) {
//原获取对象实例方法
//IAccountService accountService = new AccountServiceImpl();
//accountService.saveAccount();
//使用ApplicationContext接口获取spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//根据bean的id 获取对象的实例
IAccountService accountService = (IAccountService) ac.getBean("accountService");
accountService.saveAccount();
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(accountDao);
}
}
IOC 中 bean 标签和管理对象细节
bean标签
作用:
用于配置对象让 spring 来创建的。 默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
id:给对象在容器中提供一个唯一标识。用于获取对象。
class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
scope:指定对象的作用范围。
singleton :默认值,单例的.
prototype :多例的.
request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
global session :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 globalSession 相当于 session.
init-method:指定类中的初始化方法名称。
destroy-method:指定类中销毁方法名称。
bean的作用范围和生命周期
单例对象:
- scope="singleton" 一个应用只有一个对象的实例。它的作用范围就是整个引用。
- 生命周期:
- 对象出生:当应用加载,创建容器时,对象就被创建了。
- 对象活着:只要容器在,对象一直活着。
- 对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
多例对象:
- scope="prototype" 每次访问对象时,都会重新创建对象实例。
- 生命周期:
- 对象出生:当使用对象时,创建新的对象实例。
- 对象活着:只要对象在使用中,就一直活着。
- 对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
依赖注入
依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。
我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。 ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。
构造函数注入
使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置 的方式,让 spring 框架来为我们注入。
实例:
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 AccountServiceImpl(){
}
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccout();
System.out.println("name:"+name+",age:"+age+",birthday:"+birthday);
}
}
<!--配置Service-->
<bean id="accountService" class="org.example.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="zhangsan"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!--配置Dao-->
<bean id="accountDao" class="org.example.dao.impl.AccountDaoImpl"></bean>
<!--获取当前时间-->
<bean id="now" class="java.util.Date"></bean>
public class App {
public static void main( String[] args ) {
//原获取对象实例方法
//IAccountService accountService = new AccountServiceImpl();
//accountService.saveAccount();
//使用ApplicationContext接口获取spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//根据bean的id 获取对象的实例
IAccountService accountService = (IAccountService) ac.getBean("accountService");
accountService.saveAccount();
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(accountDao);
}
}
输出结果:
保存了账户!
name:zhangsan,age:18,birthday:Mon Nov 02 15:26:02 CST 2020
org.example.dao.impl.AccountDaoImpl@1d16f93d
使用构造函数的方式,给 service 中的属性传值 要求: 类中需要提供一个对应参数列表的构造函数。
涉及的标签:
constructor-arg 属性:
index:指定参数在构造函数参数列表的索引位置
type:指定参数在构造函数中的数据类型
name:指定参数在构造函数中的名称
=上面三个都是找给谁赋值,下面两个指的是赋什么值的========
value:它能赋的值是基本数据类型和 String 类型
ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
set方法注入
public class AccountServiceImpl implements IAccountService {
private String name;
private Integer age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccout();
System.out.println("name:"+name+",age:"+age+",birthday:"+birthday);
}
}
<bean id="accountService" class="org.example.service.impl.AccountServiceImpl">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
<property name="birthday" ref="now"></property>
</bean>
通过配置文件给 bean 中的属性传值:
使用 set 方法的方式 涉及的标签: property
属性:
name:找的是类中 set 方法后面的部分
ref:给属性赋值是其他 bean 类型的
value:给属性赋值是基本数据类型和 string 类型的
实际开发中,此种方式用的较多。
注入属性集合
是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。 我们这里介绍注入数组,List,Set,Map,Properties。
示例:
public class AccountServiceImpl implements IAccountService {
private String name;
private Integer age;
private Date birthday;
private String[] myStrs;
private List<String> myList;
private Set<String> mySet;
private Map<String,String> myMap;
private Properties myProps;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String[] getMyStrs() {
return myStrs;
}
public void setMyStrs(String[] myStrs) {
this.myStrs = myStrs;
}
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
public Set<String> getMySet() {
return mySet;
}
public void setMySet(Set<String> mySet) {
this.mySet = mySet;
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
public Properties getMyProps() {
return myProps;
}
public void setMyProps(Properties myProps) {
this.myProps = myProps;
}
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccout();
System.out.println("name:"+name+",age:"+age+",birthday:"+birthday);
System.out.println(Arrays.toString(myStrs));
System.out.println(myList);
System.out.println(mySet);
System.out.println(myMap);
System.out.println(myProps);
}
}
<bean id="accountService" class="org.example.service.impl.AccountServiceImpl">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
<property name="birthday" ref="now"></property>
<!--数组-->
<property name="myStrs">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<!--list集合-->
<property name="myList">
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<!--set集合-->
<property name="mySet">
<set>
<value>abc</value>
<value>def</value>
<value>ghi</value>
</set>
</property>
<!--Map集合-->
<property name="myMap">
<map>
<entry key="aaa" value="123"></entry>
<entry key="bbb" value="234"></entry>
</map>
</property>
<!--properties集合-->
<property name="myProps">
<props>
<prop key="aaa">123</prop>
</props>
</property>
</bean>
输出结果:
保存了账户!
name:zhangsan,age:18,birthday:Mon Nov 02 15:45:58 CST 2020
[AAA, BBB, CCC]
[aaa, bbb, ccc]
[abc, def, ghi]
{aaa=123, bbb=234}
{aaa=123}
org.example.dao.impl.AccountDaoImpl@7fac631b
- 注入集合数据 List 结构的:
array,list,set
Map 结构的:
map,entry,props,prop
在注入集合数据时,只要结构相同,标签可以互换
基于注解的IOC配置
学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样 的,都是要降低程序间的耦合。只是配置的形式不一样。
用于创建对象的注解
相当于:
@Component
作用: 把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
属性: value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。
@Controller @Service @Repository
他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。 他们只不过是提供了更加明确的语义化。
@Controller:一般用于表现层的注解。
@Service:一般用于业务层的注解。
@Repository:一般用于持久层的注解。
细节:如果注解中有且只有一个属性要赋值时,且名称是 value,value 在赋值是可以不写。
用于注入数据的注解
相当于:
@Autowired
作用: 自动按照类型注入。
当使用注解注入属性时,set 方法可以省略。
它只能注入其他 bean 类型。
当有多个 类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到 就报错。
实例:
bean.xml配置
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.test"></context:component-scan>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=UTC&useSSL=false&rewriteBatchedStatements=true"></property>
<property name="user" value="root"></property>
<property name="password" value="Xm@529401"></property>
</bean>
<!-- 配置queryrunner -->
<bean id="qr" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 注入数据源 -->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
Dao实现类
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao{
@Autowired
private QueryRunner qr;
....
}
Service实现类
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
}
测试:
@Test
public void testAop() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = (IAccountService) ac.getBean("accountService");
as.saveAccount();
}
@Qualifier
作用: 在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowire 一起使用;但是给方法参数注入时,可以独立使用。
属性: value:指定 bean 的 id。
@Autowired
@Qualifier(accountDao1)
Private IAccountDao accountDao = null;
@Resource
作用: 直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
属性: name:指定 bean 的 id。
@Resource(name="accountDao1")
Private IAccountDao accountDao = null;
这是详细一些的用法,说一下@Resource的装配顺序:
(1)、@Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配
(2)、指定了name或者type则根据指定的类型去匹配bean
(3)、指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都将报错
然后,区分一下@Autowired和@Resource两个注解的区别:
(1)、@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配
(2)、@Autowired是Spring的注解,@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了
Spring属于第三方的,J2EE是Java自己的东西,因此,建议使用@Resource注解,以减少代码和Spring之间的耦合。
@Value
作用: 注入基本数据类型和 String 类型数据的
属性: value:用于指定值
用于改变作用范围的
相当于:
@Scope
作用: 指定 bean 的作用范围。
属性: value:指定范围的值。 取值:singleton prototype request session globalsession
和生命周期相关
相当于:
@PostConstruct
作用: 用于指定初始化方法。
@PreDestroy
作用: 用于指定销毁方法。
其它注解
@Configuration
作用: 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。
属性: value:用于指定配置类的字节码
@ComponentScan
作用: 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的: 是一样的。
属性: basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。
@Bean
作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
属性: name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。
@PropertySource
作用:用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
属性: value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:
@Import
作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问 题。
属性: value[]:用于指定其他配置类的字节码。
AOP概述
AOP:全称是 Aspect Oriented Programming 即:面向切面编程。
简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的 基础上,对我们的已有方法进行增强。
AOP的作用及优势
作用: 在程序运行期间,不修改源码对已有方法进行增强。
优势: 减少重复代码; 提高开发效率; 维护方便;
AOP的实现方式
使用动态代理技术
AOP相关术语
Joinpoint(连接点): 所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的 连接点。
Pointcut(切入点): 所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。
Advice(通知/增强): 所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
Introduction(引介): 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方 法或 Field。
**Target(目标对象): **代理的目标对象。
Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
Proxy(代理): 一个类被 AOP 织入增强后,就产生一个结果代理类。
Aspect(切面): 是切入点和通知(引介)的结合。
基于XML的AOP配置
service实现类
public class AccountServiceImpl implements IAccountService {
public void saveAccount(String name,Integer age) {
//int i=1/0;
System.out.println(name+":"+age+";保存方法执行了。。。");
}
}
定义增强方法
/**
* 用于记录日志的工具类,提供了日志的公用方法
* @author HP
*
*/
public class Logger {
public void printLog() {
System.out.println("Logger类中的printLog方法执行了。。。。");
}
public void beforeLog() {
System.out.println("前置通知的方法执行了。。。");
}
public void afterReturningLog() {
System.out.println("后置通知的方法执行了。。。");
}
public void afterThrowingLog() {
System.out.println("异常通知的方法执行了。。。");
}
public void afterLog() {
System.out.println("最终通知的方法执行了。。。。");
}
/**
* 环绕通知
* 问题分析:
* 当执行环绕通知时,事务的方法不再执行。
* 原因:动态代理的整个invocation方法(增强方法)即环绕通知,业务方法嵌套在invocation方法中。
* 解决:spring框架为我们提供了一个接口:ProceedingJoinPoint。该借口有一个方法:proceed(),此方法就相当于明确调用切入点方法。
* spring的环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
*/
public Object aroundLog(ProceedingJoinPoint pjp) {
Object result = null;
try {
//得到方法执行所需的参数
Object[] args=pjp.getArgs();
System.out.println("我是前置方法");
//调用业务层放(切入点方法)
result=pjp.proceed(args);
System.out.println("我是后置方法");
return result;
} catch (Throwable e) {
System.out.println("我是异常方法");
throw new RuntimeException(e);
}finally {
System.out.println("我是最后执行的方法");
}
}
}
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">
<!-- 配置Service对象 -->
<bean id="accountService" class="com.test.service.impl.AccountServiceImpl"></bean>
<!-- 配置Logger对象 -->
<bean id="logger" class="com.test.utils.Logger"></bean>
<!-- 配置AOP,将logger的方法插入到accoutService对象的方法中 -->
<!-- spring中关于XML的AOP配置
1、把通知Bean(增强方法的对象)交给spring管理
2、使用aop:config标签表名开始AOP的配置
3、使用aop:aspect标签表明配置切面(即aop与增强方法对象关联
id属性:切面的唯一标识
ref属性:通知bean属性的id
4、在aop:aspect标签内部使用对应的标签来配置通知的类型
aop:before:表示配置前置通知
methed属性:用于指定使用通知对象中的某个方法
pointcut属性:用于指定切入点表达式,该表达式的含义指对哪些方法进行增强
切入点表达式的写法:
关键字:execution(表达式)
表达式:
访问修饰符 返回值 包名 类名 方法名(参数列表)
public void com.test.service.impl.AccountService.saveAccount()
修饰符可以省略
void com.test.service.impl.AccountService.saveAccount()
返回值可以使用通配符,表示任意返回值
* com.itheima.service.impl.AccountServiceImpl.saveAccount()
包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.
* *.*.*.*.AccountServiceImpl.saveAccount())
包名可以使用..表示当前包及其子包
* *..AccountServiceImpl.saveAccount()
类名和方法名都可以使用*来实现通配
* *..*.*()
参数列表:
可以直接写数据类型:
基本类型直接写名称 int
引用类型写包名.类名的方式 java.lang.String
可以使用通配符表示任意类型,但是必须有参数
可以使用..表示有无参数均可,有参数可以是任意类型
全通配写法:
* *..*.*(..)
实际开发中切入点表达式的通常写法:
切到业务层实现类下的所有方法
* com.itheima.service.impl.*.*(..)
) -->
<!--
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="printLog" pointcut="execution(public void com.test.service.impl.AccountServiceImpl.saveAccount())"/>
</aop:aspect>
</aop:config>
-->
<!-- 开始配置AOP -->
<aop:config>
<!-- 配置切入点表达式,expressssion属性用于指定表达式内容
此标签可以卸载aop:aspect标签内,只能当前切面使用
也可以写在aop:aspect标签外,所有切面可用 -->
<aop:pointcut expression="execution(* com.test.service.impl.*.*(..))" id="pt1"/>
<!-- 配置切面 -->
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置前置通知 beforeLog为logger类的方法
<aop:before method="beforeLog" pointcut-ref="pt1"/>
-->
<!-- 配置后置通知 afterReturningLog为logger类的方法
<aop:after-returning method="afterReturningLog" pointcut-ref="pt1"/>
-->
<!-- 配置异常通知 afterThrowingLog为logger类的方法
<aop:after-throwing method="afterThrowingLog" pointcut-ref="pt1"/>
-->
<!-- 配置最终通知 afterLog为logger类的方法
<aop:after method="afterLog" pointcut-ref="pt1"/>
-->
<!-- 配置环绕通知 aroundLog为logger类的方法-->
<aop:around method="aroundLog" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
</beans>
测试:
@Test
public void testAop() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = (IAccountService) ac.getBean("accountService");
as.saveAccount("zhangsan",17);
}
---------------------------------测试结果-------------------------------------
我是前置方法
zhangsan:17;保存方法执行了。。。
我是后置方法
我是最后执行的方法
基于注解的AOP配置
bean.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring容器创建时需要扫描的包 -->
<context:component-scan base-package="com.test"></context:component-scan>
<!-- 开启AOP的注解配置 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Service实现类
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("保存方法执行了。。。");
}
}
定义增强方法
@Component("logger")
@Aspect //表示当前类是一个切面类(增强方法类)
public class Logger {
//切入点表达式
@Pointcut("execution(* com.test.service.impl.*.*(..))")
private void pt() {}
public void printLog() {
System.out.println("Logger类中的printLog方法执行了。。。。");
}
//@Before(value = "pt()")
public void beforeLog() {
System.out.println("前置通知的方法执行了。。。");
}
//@AfterReturning("pt()")
public void afterReturningLog() {
System.out.println("后置通知的方法执行了。。。");
}
//@AfterThrowing("pt()")
public void afterThrowingLog() {
System.out.println("异常通知的方法执行了。。。");
}
//@After("pt()")
public void afterLog() {
System.out.println("最终通知的方法执行了。。。。");
}
/**
* 环绕通知
* 问题分析:
* 当执行环绕通知时,事务的方法不再执行。
* 原因:动态代理的整个invocation方法(增强方法)即环绕通知,业务方法嵌套在invocation方法中。
* 解决:spring框架为我们提供了一个接口:ProceedingJoinPoint。该借口有一个方法:proceed(),此方法就相当于明确调用切入点方法。
* spring的环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
*/
@Around("pt()")
public Object aroundLog(ProceedingJoinPoint pjp) {
Object result = null;
try {
//得到方法执行所需的参数
Object[] args=pjp.getArgs();
System.out.println("我是前置方法");
//调用业务层放(切入点方法)
result=pjp.proceed(args);
System.out.println("我是后置方法");
return result;
} catch (Throwable e) {
System.out.println("我是异常方法");
throw new RuntimeException(e);
}finally {
System.out.println("我是最后执行的方法");
}
}
}
测试
@Test
public void testAop() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = (IAccountService) ac.getBean("accountService");
as.saveAccount();
}
AOP注解:
注意问题:当使用AOP注解时,AOP的通知方法执行顺序与XML配置的不一致;
XML配置的执行顺序:前置通知--》业务方法执行--》后置通知/异常通知--》最终通知
AOP注解的执行顺序:前置通知--》业务方法执行--》最终通知--》后置通知/异常通知
AOP环绕通知执行顺序与XML的执行顺序一致,建议用AOP注解时使用环绕通知(环绕通知的方法代码是手动配置的,并不是由AOP容器去进行配置)
Spring中的事务控制
需要明确的概念
第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方 案。
第二:spring 框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在 spring-tx-5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我 们学习的重点是使用配置的方式实现。
Spring中事务控制的API介绍
PlatformTransactionManager接口(了解即可)
PlatformTransactionManager接口提供操作事务的方法,包含有3个具体的操作
//获取事务状态信息
TransactionStatus getTransaction(TransactionDefinition definition)
//提交事务
void commit(TransactionStatus status)
//回滚事务
void rollback(TransactionStatus status)
在开发中都是使用它的实现类
真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager
使用 Spring JDBC 或 iBatis 进行持久化数据时使用 org.springframework.orm.hibernate5.HibernateTransactionManager
使用 Hibernate 版本进行持久化数据时使用
TransactionDefinition
它是事务的定义信息对象,有如下方法
获取事务对象名称
String getName()
获取事务隔离级
int getIsolationLevel()
获取事务传播行为
int getPropagationBehavior()
获取事务超时时间
int getTimeout()
获取事务是否只读
boolean isReadOnly()
事务的隔离级别
事务隔离级别反映事务提交并发访问时的处理态度
ISOLATION_DEFAULT
默认级别,归属下列某一种
ISOLATION_READ_UNCOMMOTTED
可以读取未提交数据
ISOLATION_READ_COMMITED
只能读取已提交数据,解决脏读问题(Oracle默认级别)
ISOLATION_REPEATABLE_READ
是否读取其他事务提交修改后的数据,解决不可重复读问题(MySQL默认级别)
ISOLATION_SERIALIZABLE
是否读取其他事务提交添加后的数据,解决幻影读问题
事务的传播行为
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选
择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作。
超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
是否是只读事务
建议查询时设置为只读
TransactionStatus
此接口提供的是事务具体的运行状态,包含有6个具体的操作
刷新事务
void flush()
获取是否存在存储点
boolean hasSavepoint()
获取事务是否完成
boolean isCompleted()
获取事务是否为新的事务
boolean ieNewTransaction()
获取事务是否回滚
boolean isRollbackOnly()
设置事务回滚
void setRollackOnly()
基于XML的声明式事务控制
1、配置事务管理器
<!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入 DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
2、配置事务的通知引用事务管理器
<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
</tx:advice>
3、配置事务的属性
<!--在 tx:advice 标签内部 配置事务的属性 -->
<tx:attributes>
<!-- 指定方法名称:是业务核心方法
read-only:是否是只读事务。默认 false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回
滚。没有默认值,任何异常都回滚。
-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
4、配置AOP切入点表达式
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
id="pt1"/>
</aop:config>
5、配置切入点表达式和事务通知的对应关系
<!-- 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
基于注解的配置方式
1、配置事务管理器并注入数据源
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
2、在业务层使用@Transactional
注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
//int i=1/0;
accountDao.updateAccount(target);
}
}
该注解的属性和 xml 中的属性含义一致。
该注解可以出现在接口上,类上和方法上。 出现接口上,表示该接口的所有实现类都有事务支持。 出现在类上,表示类中所有方法有事务支持 出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口
3、在配置文件中开启spring对注解事务的支持
<!-- 开启 spring 对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>