一、 AOP思想
-
AOP(Aspect Oriented Programming),是面向切面编程的技术,把一个个的横切关注点放到某个模块中去,称之为切面。切面的目的就是功能增强,吧需要做的事情插入切面,这种面向切面编程的思想就是 AOP 思想了。
动态代理就可以实现 AOP
作用:
把业务方法中与业务无关的操作抽离到不同的对象中,最后使用动态代理的方式组合起来,动态地为类增加功能。
AOP术语
Joinpoint:连接点,一般指需要被增强的方法。where:去哪里做增强。
Pointcut:切入点,哪些包中的哪些类中的哪些方法,可认为是连接点的集合。where:去哪些地方做增强。
Advice:增强,当拦截到 Joinpoint 之后,在方法执行的什么时机(when)做什么样(what)的增强。根据时机分为:前置增强、后置增强、异常增强、最终增强、环绕增强。
Aspect:切面,Pointcut + Advice,去哪些地方 + 在什么时候 + 做什么增强。
Target:被代理的目标对象。
Weaving:织入,把 Advice 加到 Target 上之后,创建出 Proxy 对象的过程。
Proxy:一个类被 AOP 织入增强后,产生的代理类。
二、 AOP 实现及Pointcut表达式
AOP思想由Spring AOP(能与 Spring 无缝整合)和 AspectJ 实现 ,AspectJ 是一个面向切面的框架
-
AspectJ切入点语法
切入点语法通配符
* : 匹配任何部分,只能表示一个单词
.. : 可用于全限定名中和方法参数中,分别表示子包和 0 到 N 个参数
例子:
注意第一个星符号后面有空格。
execution(* cn.wolfcode.ssm.service.impl.*ServiceImpl.*(..))
三、使用XML配置AOP
添加依赖
pring-aop-5.0.8.RELEASE-sources
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
XML文件添加AOP约束,编写配置

编写单元测试

变更使用CGLIB
在applicationContext.xml配置如下:

四、 注解配置AOP

变更使用CGLIB
在applicationContext.xml配置如下

五、 SSM集成
- Spring 集成 MyBatis
业务对象、Mapper对象等都交由Spring容器管理
Spring IoC 和DI来完成对象创建及其属性注入
再使用AOP来配置事务
添加依赖及插件
配置SessionSqlFactory

编写Mapper接口及对应Mapper XML文件


在配置SqlSessionFactory对象关联Mapper映射文件(可以不配置):

配置Mapper接口的代理对象

配置业务层对象


配置业务对象

编写单元测试

六、注解方式集成MyBatis
配置Mapper接口扫描器

使用注解方式配置业务对象
在业务类上贴IoC注解和DI注解

配置第三方解析程序
在applicationContext.xml中配置如下:

七、 Spring对事务支持
使用Spring管理事务的时候,针对不同的持久化技术选用不同的事务管理器:
- JDBC / MyBatis使用DataSourceTransactionManager
- Hibernate使用HibernateTransactionManager
- JPA使用JpaTransactionManager
Spring实现事务的方式:
编程式事务:通过编写代码来管理事务;
声明式事务:通过XML配置或注解来管理事务。
八、使用XML配置事务

-
通用事务配置
方法名约定俗成,所以自己事务配置好了,业务方法名切记不要乱取了。(get,set)
九、 注解配置事务
为业务类贴注解

XML配置

Transactional注解使用
-
Transactional注解可以贴在接口或实现类上,即类或接口上的事务的配置是通用与整个类或接口的的方法;而也可以贴方法上,即方法上的的事务的配置仅限于被贴的方法。
-
若想强制使用CGLIB动态代理,则修改<tx:annotation-drive>上的属性 proxy-target-class修改为true即可。
网友评论