1、Spring中AOP的术语和细节
1、概述
含义: 面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。
作用: 将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。
2、需要用到的包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
3、术语
JoinPoint(连接点):
被拦截到的点,连接业务和增强方法中的点,也就是service接口中的方法
PointCut(切入点):
对哪些JoinPoint进行拦截的定义。也就是service中被增强的方法(所有的切入点都是连接点),未被增强的只是连接点
Advice(通知/增强):
通知是指拦截到JoinPoint之后要做的事情,实质就是事务支持
通知的类型:
前置通知(invoke执行之前)、后置通知(invoke执行之后)、异常通知(catch中)、最终通知(finally中)、环绕通知(整个invoke方法在执行就是环绕通知。环绕通知中有明确的切入点方法调用)
Introduction(引介):
引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态的添加一些方法或Field
Target(目标对象):
被代理对象
Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。—代理后返回一个代理对象
Proxy(代理):
代理对象
Aspect(切面):
切入点和通知的结合—点点成面
补充:
在AOP中切面就是与业务逻辑独立,但又垂直存在于业务逻辑的代码结构中的通用功能组合;切面与业务逻辑相交的点就是切点;连接点就是把业务逻辑离散化后的关键节点;切点属于连接点,是连接点的子集;Advice(增强)就是切面在切点上要执行的功能增加的具体操作;在切点上可以把要完成增强操作的目标对象(Target)连接到切面里,这个连接的方式就叫织入。
4、需要明确的事:
1、开发阶段
编写核心业务代码
把公用代码抽取出来,制作成通知
配置文件中,声明切入点和通知之间的关系
2、运行阶段
Spring框架监控切入点方法的运行,一旦监控到切入点方法被运行,使用代理机制。动态创建目标对象的代理对象,并作相应的代理。
2、Spring基于XML的AOP配置步骤
注意:在SSM中引入AOP时,需要将其配置在SpringMVC的配置文件中
1、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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
2、service引入
3、把通知bean引入
4、使用aop:config标签表明开始aop配置
5、使用aop:aspect标签表明配置切面
id:唯一标识
ref:指定通知bean的id
6、在aop:aspect标签的内部使用对应的标签配置通知类型
aop:before----前置通知
aop:after-returning ----后置通知
aop:after-throwing ----异常通知
aop:after ----最终通知
属性:
a、method:用于指定通知方法
b、pointcut:用于指定切入点表达式(方法)
c、切入点表达式写法:
**关键字:*execution(表达式)
表达式:
访问修饰符 返回值 包名.包名.包名.包名。。。类名.方法名(参数)
标准写法:
public void com.dhcc.my.service.imp.AccountServiceImp.saveAccount()
全通配写法:
1、访问修饰符可以省略
2、返回值可使用通配符,表示任意返回值
3、包名可以使用通配符,表示任意包 ,几个包写几个
4、包名可以使用…来表示当前包及其子包
4、类名和方法名都可以使用*来实现
5、方法参数可用…来表示任意参数
如下:
- ….*(…)
开发中实际写法为指向业务层实现类的所有方法
通用化切入点表达式:
在aop:aspect标签中配置,必须写在切面之前,并在上述通知类型中中通过pointcut-ref引入
<aop:pointcut id=“” expression=“”/>
也可写在aop:aspect外,可全局引用
7、示例
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- <context:component-scan base-package="com.my"></context:component-scan> -->
<bean id="serviceMethods" class="com.my.test.ServiceMethods"></bean>
<bean id="useAdvice" class="com.my.test.UseAdvice"></bean>
<aop:config>
<aop:aspect id="useAdviceAspect" ref="useAdvice">
<aop:pointcut expression="execution(* com.my.test.ServiceMethods.method*(..))" id="serviceMethodPointCut"/>
<aop:before method="beforeAdvice" pointcut-ref="serviceMethodPointCut"/>
<aop:after-returning method="afterReturning" pointcut-ref="serviceMethodPointCut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="serviceMethodPointCut"/>
<aop:after method="after" pointcut-ref="serviceMethodPointCut"/>
</aop:aspect>
</aop:config>
</beans>
Java代码
public class TestMain {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
ServiceMethods serviceM = (ServiceMethods) app.getBean("serviceMethods");
serviceM.methodA();
serviceM.methodB();
}
}
class ServiceMethods {
public void methodA() {
System.out.println("A方法执行!");
}
public void methodB() {
System.out.println("B方法执行!");
}
}
class UseAdvice {
public void beforeAdvice() {
System.out.println("前置通知");
}
public void afterReturning() {
System.out.println("后置通知");
}
public void afterThrowing() {
System.out.println("异常通知");
}
public void after() {
System.out.println("最终通知");
}
}
3、基于注解的AOP配置
1、加入context名称空间
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
2、配置spring创建容器时扫描的包
<context:component-scan base-package="包"></context:component-scan>
3、配置spring开启注解AOP的支持
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4、@Aspect表示当前类是一个切面类
5、通知类型
@Before----前置通知
@AfterReturning----后置通知
@AfterThrowing—异常通知
@After----最终通知
@Around----环绕通知
6、切入点表达式
@Pointcut(“execution(…)”)
public void a(){} -----a指向切面方法集,在上述通知类型调用 如@Before(“a()”)
spring基于注解AOP通知类型有调用顺序问题 环绕通知无问题
7、使用纯注解的方式
@Configuration
@ComponentScan(basePackage=“包”)
@EnableAspectJAutoProxy----开启spring对AspectJ的支持
8、示例
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置Spring创建容器时扫描的包 -->
<context:component-scan base-package="com.my"></context:component-scan>
<!-- 配置spring开启注解AOP的支持 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Java代码
public class TestMain {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
ServiceMethods serviceM = (ServiceMethods) app.getBean("serviceMethods");
serviceM.methodA();
serviceM.methodB();
}
}
//注入容器
@Service
class ServiceMethods {
public void methodA() {
System.out.println("A方法执行!");
}
public void methodB() {
System.out.println("B方法执行!");
}
}
@Component
//值定切面
@Aspect
class UseAdvice {
//值定切点
@Pointcut("execution(* com.my.test.ServiceMethods.method*(..))")
private void executePoint() {}
@Before(value = "executePoint()")
public void beforeAdvice() {
System.out.println("前置通知");
}
@AfterReturning(value="executePoint()")
public void afterReturning() {
System.out.println("后置通知");
}
@AfterThrowing(value="executePoint()")
public void afterThrowing() {
System.out.println("异常通知");
}
@After(value = "executePoint()")
public void after() {
System.out.println("最终通知");
}
}
4、Spring中事物控制
1、概述
事务就是对一系列的数据库操作进行统一的提交或回滚操作,比如说做一个转账功能,要更改帐户两边的数据,这时候就必须要用事务才能算是严谨的做法。要么成功,要么失败,保持数据一致性。如果中间有一个操作出现异常,那么回滚之前的所有操作。
第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
第二:spring 框架为我们提供了一组事务控制的接口。这组接口是在spring-tx-5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。
2、Spring中事务控制的API
1、PlatformTransactionManager
此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:
2、真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring JDBC 或 iBatis 进行持久化数据时使用
org.springframework.orm.hibernate5.HibernateTransactionManager 使用
Hibernate 版本进行持久化数据时使用
3、TransactionDefinition
它是事务的定义信息对象,里面有如下方法:
4、事务的隔离级别
5、事务的传播行为
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
6、超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
7、TransactionStatus
8、<tx:method />标签的属性
name:方法名的匹配模式,通知根据该模式寻找匹配的方法。该属性可以使用asterisk (*)通配符
propagation:设定事务定义所用的传播级别
isolation:设定事务的隔离级别
timeout:指定事务的超时(单位为秒)
read-only:该属性为true指示事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)
no-rollback-for:以逗号分隔的异常类的列表,目标方法可以抛出这些异常而不会导致通知执行回滚
rollback-for:以逗号分隔的异常类的列表,当目标方法抛出这些异常时会导致通知执行回滚。默认情况下,该列表为空,因此不在no-rollback-for列表中的任何运行时异常都会导致回滚
3、基于XML的声明式事务控制(配置方式)
1、引入jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
2、创建所需的类
public class TestMain {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
PersonServiceImpl p = (PersonServiceImpl) app.getBean("personServiceImpl");
p.savePerson();
}
}
class PersonDaoImpl extends JdbcDaoSupport{
public void savePerson(String sql) {
this.getJdbcTemplate().execute(sql);
}
}
class PersonServiceImpl{
private PersonDaoImpl personDao;
public void setDao(PersonDaoImpl personDao) {
this.personDao = personDao;
}
public void savePerson() {
personDao.savePerson("INSERT INTO test1 (ID,NAME ) VALUES(1,'xixi')");
int a=1/0;
personDao.savePerson("INSERT INTO test1 (ID,NAME ) VALUES(2,'xixi')");
}
}
3、配置文件
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<!-- 配置数据源 -->
<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/my_test?serverTimezone=GMT%2B8"></property>
<property name="username" value="root"></property>
<property name="password" value="666666"></property>
</bean>
<bean id="personDaoImpl" class="com.my.test.PersonDaoImpl">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="personServiceImpl" class="com.my.test.PersonServiceImpl">
<property name="dao">
<ref bean="personDaoImpl" />
</property>
</bean>
<!-- 事务管理器 告诉spring容器要采用什么样的技术处理事务 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<tx:advice id="tx" transaction-manager="transactionManager">
<tx:attributes>
<!--告知事务处理的策略-->
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"
read-only="false" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut
expression="execution(* com.my.test.PersonServiceImpl.*(..))"
id="perform" />
<aop:advisor advice-ref="tx" pointcut-ref="perform" />
</aop:config>
</beans>
4、基于注解的配置方式
配置文件
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.my"></context:component-scan>
<!-- 配置数据源 -->
<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/my_test?serverTimezone=GMT%2B8"></property>
<property name="username" value="root"></property>
<property name="password" value="666666"></property>
</bean>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务管理器 告诉spring容器要采用什么样的技术处理事务 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- 开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
Java代码
public class TestMain {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
A p = (A) app.getBean("a");
p.sayA();
}
}
@Service
@Transactional
class A{
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
public void sayA() {
jdbcTemplate.update("INSERT INTO test1 (ID,NAME ) VALUES(1,'xixi')");
int i = 1/0;
jdbcTemplate.update("INSERT INTO test1 (ID,NAME ) VALUES(2,'xixi1')");
}
}