美文网首页
Spring的aop配置和简单事务配置

Spring的aop配置和简单事务配置

作者: playman | 来源:发表于2018-06-24 22:04 被阅读0次

aop配置和事务的配置

环境

  • jdk1.7
  • tomcat7.0
  • spring3.1.1
  • hibernate4.1.4

自定义aop的配置(applicationContext.xml中配置)

自定义advise的类

package com.ben.second;
import org.aspectj.lang.JoinPoint;
public class MyAdvice{
    public void before(JoinPoint joinPoint){
        System.out.println("之前的附加操作");
    }
}
注意:要传入参数

main方法

package com.ben.second;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoMain {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TargetInterface target = context.getBean("targetClass", TargetInterface.class);
        target.doAnyMethod();
    }
}

配置文件

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean name="targetClass" class="com.ben.second.TargetClass"></bean>

    <bean name="myAdvice" class="com.ben.second.MyAdvice"></bean>

    <aop:config>
        <!-- 配置切面的装备类 -->
        <aop:aspect id="aspect" ref="myAdvice">
            <!-- 配置在哪个方法上执行切面的附加方法 -->
            <!-- expression中的格式是 execution([返回类型] [包名路径].[类名].[方法名](参数..)-->
            <aop:pointcut expression="execution(* com.ben.second.*.*(..))" id="targetMgr"/>

            <aop:before method="before" pointcut-ref="targetMgr"/>
        </aop:aspect>
    </aop:config>


</beans>
around方法
private Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("做主业务的之前操作");
    System.out.println(pjp.getKind());
    System.out.println(pjp.getThis());
    System.out.println(pjp.getTarget());
    System.out.println(Arrays.toString(pjp.getArgs()));
    System.out.println(pjp.getClass());
    System.out.println(pjp.getSignature());
    System.out.println(pjp.getSourceLocation());
    System.out.println(pjp.getStaticPart());
    // 这个对象的获取要放在其它附加操作的中间,那么才嫩形成一个包围的状态,如果直接写在return的后面,就会形成在最后才调用主要业务
    Object obj = pjp.proceed();
    System.out.println("做主业务之后的操作");
    return obj;
}

打印内容

做主业务的之前操作
method-execution
com.ben.second.TargetClass@6bb6f7fc
com.ben.second.TargetClass@6bb6f7fc
[]
class org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint
void com.ben.second.TargetInterface.doAnyMethod()
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@617d99d7
execution(void com.ben.second.TargetInterface.doAnyMethod())
做的主要方法
做主业务之后的操作

配置

<aop:around method="doAround" pointcut-ref="targetMgr"/>
throwing抛出异常的操作
private void throwing(JoinPoint joinPoint,Throwable ex){
    System.out.println("出错处理");
    System.out.println(ex.getMessage());
}
打印内容,如果没有出错就不会产生



配置文件

<aop:after-throwing method="throwing" throwing="ex" pointcut-ref="targetMgr"/>
注:另外还有after的操作,return的操作等。配置相似,但作用的位置不同,根据情况选择即可
<aop:after method="" pointcut-ref=""/>
<aop:after-returning method="" pointcut-ref=""/>
<aop:after-throwing method="" pointcut-ref=""/>

自定义aop的配置(注解配置)

配置注解的话,需要在applicationContext.xml中进行配置

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

两个bean的配置照样

<bean name="targetClass" class="com.ben.second.TargetClass"></bean>
<bean name="myAdvice" class="com.ben.second.MyAdvice"></bean>

在MyAdvice中的书写注释内容

package com.ben.second;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAdvice {
//  做一个空方法,作为识别使用
    @Pointcut("execution(* do*(..))")
    public void aspectPoint(){
    }

    @Before(value="aspectPoint()")
    public void before(JoinPoint joinPoint) {
        System.out.println("之前的附加操作");
    }

    @Around(value="aspectPoint()")
    private Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("做主业务的之前操作");
        System.out.println(pjp.getKind());
        System.out.println(pjp.getThis());
        System.out.println(pjp.getTarget());
        System.out.println(Arrays.toString(pjp.getArgs()));
        System.out.println(pjp.getClass());
        System.out.println(pjp.getSignature());
        System.out.println(pjp.getSourceLocation());
        System.out.println(pjp.getStaticPart());
        // 这个对象的获取要放在其它附加操作的中间,那么才嫩形成一个包围的状态,如果直接写在return的后面,就会形成在最后才调用主要业务
        Object obj = pjp.proceed();
        System.out.println("做主业务之后的操作");
        return obj;
    }

    @AfterThrowing(value="aspectPoint()",throwing="ex")
    private void throwing(JoinPoint joinPoint,Throwable ex){
        System.out.println("出错处理");
        System.out.println(ex.getMessage());
    }
    @AfterReturning(value="aspectPoint()", returning="retVal")
    public void afterReturningAdvice(JoinPoint joinPoint, String retVal) {
        System.out.println("返回处理");
        System.out.println(retVal);
    }
}

打印值

之前的附加操作
做主业务的之前操作
method-execution
com.ben.second.TargetClass@67e4d68
com.ben.second.TargetClass@67e4d68
[]
class org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint
void com.ben.second.TargetInterface.doAnyMethod()
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@23f9a9f4
execution(void com.ben.second.TargetInterface.doAnyMethod())
做的主要方法
返回处理
null
做主业务之后的操作

注意

  • 注解的方式比较简单,但是要注意引入aspect的相关jar包。
  • 同时在方法里面写一个识别的参考方法。

事务的配置

事务的配置,主要是对数据库的使用进行配置,以免出现脏读等操作。
四个原则
  • 一致性(Consistency)
  • 隔离性(Isolation)
  • 原子性(Atomic)
  • 持续性(Durability)

通过xml文件配置事务

通用配置

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>

切面配置

<!-- 配置切面 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- 配置属性 -->
    <tx:attributes>
        <tx:method name="save" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<!-- aop配置切面 -->
<aop:config>
    <aop:pointcut expression="execution(* com.ben.dao.impl.*.*(..))" id="pointCut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>

通过注解配置事务

首先清除上面的配置,添加一条注解配置

<tx:annotation-driven transaction-manager="transactionManager" />

在dao层中的方法上添加注解

@Transactional

当然注解中也可以配置一些内容(有些参数在最底下看,查找)

配置注意
  • transactionManager的配置若为org.springframework.orm.hibernate4.HibernateTransactionManager
  • sessionFactory的配置就得为org.springframework.orm.hibernate4.LocalSessionFactoryBean
  • 如果是hibernate5的话,也要做对应的匹配
  • 如果是hibernate3的话,sessionFactory配置org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean(注解配置)
  • 如果出现hibernate3不能转成hibernate4的错误的话,请引入这个包spring-orm-4.3.6.RELEASE.jar

其它内容

xml配置的事务参数

  • PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
  • PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
  • PROPAGATION_MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
  • PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
  • PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
  • PROPAGATION_NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。

注解配置事务的参数

  • @Transactional(propagation=Propagation.REQUIRED) 如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)
  • @Transactional(propagation=Propagation.NOT_SUPPORTED) 容器不为这个方法开启事务
  • @Transactional(propagation=Propagation.REQUIRES_NEW) 不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
  • @Transactional(propagation=Propagation.MANDATORY) 必须在一个已有的事务中执行,否则抛出异常
  • @Transactional(propagation=Propagation.NEVER) 必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
  • @Transactional(propagation=Propagation.SUPPORTS) 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.

注解timeout

  • @Transactional(timeout=30) //默认是30秒

注解的事务隔离级别

  • @Transactional(isolation = Isolation.READ_UNCOMMITTED) 读取未提交数据(会出现脏读, 不可重复读) 基本不使用
  • @Transactional(isolation = Isolation.READ_COMMITTED) 读取已提交数据(会出现不可重复读和幻读)
  • @Transactional(isolation = Isolation.REPEATABLE_READ) 可重复读(会出现幻读)
  • @Transactional(isolation = Isolation.SERIALIZABLE) 串行化

数据库创建事务解决的几种问题

  • 脏读 : 一个事务读取到另一事务未提交的更新数据
  • 不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说, 后续读取可以读到另一事务已提交的更新数据. 相反, "可重复读"在同一事务中多次读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据
  • 幻读 : 一个事务读到另一个事务已提交的insert数据

aop配置和事务的配置

环境

  • jdk1.7
  • tomcat7.0
  • spring3.1.1
  • hibernate4.1.4

自定义aop的配置(applicationContext.xml中配置)

自定义advise的类

package com.ben.second;
import org.aspectj.lang.JoinPoint;
public class MyAdvice{
    public void before(JoinPoint joinPoint){
        System.out.println("之前的附加操作");
    }
}
注意:要传入参数

main方法

package com.ben.second;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoMain {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TargetInterface target = context.getBean("targetClass", TargetInterface.class);
        target.doAnyMethod();
    }
}

配置文件

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean name="targetClass" class="com.ben.second.TargetClass"></bean>

    <bean name="myAdvice" class="com.ben.second.MyAdvice"></bean>

    <aop:config>
        <!-- 配置切面的装备类 -->
        <aop:aspect id="aspect" ref="myAdvice">
            <!-- 配置在哪个方法上执行切面的附加方法 -->
            <!-- expression中的格式是 execution([返回类型] [包名路径].[类名].[方法名](参数..)-->
            <aop:pointcut expression="execution(* com.ben.second.*.*(..))" id="targetMgr"/>

            <aop:before method="before" pointcut-ref="targetMgr"/>
        </aop:aspect>
    </aop:config>


</beans>
around方法
private Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("做主业务的之前操作");
    System.out.println(pjp.getKind());
    System.out.println(pjp.getThis());
    System.out.println(pjp.getTarget());
    System.out.println(Arrays.toString(pjp.getArgs()));
    System.out.println(pjp.getClass());
    System.out.println(pjp.getSignature());
    System.out.println(pjp.getSourceLocation());
    System.out.println(pjp.getStaticPart());
    // 这个对象的获取要放在其它附加操作的中间,那么才嫩形成一个包围的状态,如果直接写在return的后面,就会形成在最后才调用主要业务
    Object obj = pjp.proceed();
    System.out.println("做主业务之后的操作");
    return obj;
}

打印内容

做主业务的之前操作
method-execution
com.ben.second.TargetClass@6bb6f7fc
com.ben.second.TargetClass@6bb6f7fc
[]
class org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint
void com.ben.second.TargetInterface.doAnyMethod()
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@617d99d7
execution(void com.ben.second.TargetInterface.doAnyMethod())
做的主要方法
做主业务之后的操作

配置

<aop:around method="doAround" pointcut-ref="targetMgr"/>
throwing抛出异常的操作
private void throwing(JoinPoint joinPoint,Throwable ex){
    System.out.println("出错处理");
    System.out.println(ex.getMessage());
}

打印内容,如果没有出错就不会产生


配置文件

<aop:after-throwing method="throwing" throwing="ex" pointcut-ref="targetMgr"/>
注:另外还有after的操作,return的操作等。配置相似,但作用的位置不同,根据情况选择即可
<aop:after method="" pointcut-ref=""/>
<aop:after-returning method="" pointcut-ref=""/>
<aop:after-throwing method="" pointcut-ref=""/>

自定义aop的配置(注解配置)

配置注解的话,需要在applicationContext.xml中进行配置

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

两个bean的配置照样

<bean name="targetClass" class="com.ben.second.TargetClass"></bean>
<bean name="myAdvice" class="com.ben.second.MyAdvice"></bean>

在MyAdvice中的书写注释内容

package com.ben.second;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAdvice {
//  做一个空方法,作为识别使用
    @Pointcut("execution(* do*(..))")
    public void aspectPoint(){
    }

    @Before(value="aspectPoint()")
    public void before(JoinPoint joinPoint) {
        System.out.println("之前的附加操作");
    }

    @Around(value="aspectPoint()")
    private Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("做主业务的之前操作");
        System.out.println(pjp.getKind());
        System.out.println(pjp.getThis());
        System.out.println(pjp.getTarget());
        System.out.println(Arrays.toString(pjp.getArgs()));
        System.out.println(pjp.getClass());
        System.out.println(pjp.getSignature());
        System.out.println(pjp.getSourceLocation());
        System.out.println(pjp.getStaticPart());
        // 这个对象的获取要放在其它附加操作的中间,那么才嫩形成一个包围的状态,如果直接写在return的后面,就会形成在最后才调用主要业务
        Object obj = pjp.proceed();
        System.out.println("做主业务之后的操作");
        return obj;
    }

    @AfterThrowing(value="aspectPoint()",throwing="ex")
    private void throwing(JoinPoint joinPoint,Throwable ex){
        System.out.println("出错处理");
        System.out.println(ex.getMessage());
    }
    @AfterReturning(value="aspectPoint()", returning="retVal")
    public void afterReturningAdvice(JoinPoint joinPoint, String retVal) {
        System.out.println("返回处理");
        System.out.println(retVal);
    }
}

打印值

之前的附加操作
做主业务的之前操作
method-execution
com.ben.second.TargetClass@67e4d68
com.ben.second.TargetClass@67e4d68
[]
class org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint
void com.ben.second.TargetInterface.doAnyMethod()
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@23f9a9f4
execution(void com.ben.second.TargetInterface.doAnyMethod())
做的主要方法
返回处理
null
做主业务之后的操作

注意

  • 注解的方式比较简单,但是要注意引入aspect的相关jar包。
  • 同时在方法里面写一个识别的参考方法。

事务的配置

事务的配置,主要是对数据库的使用进行配置,以免出现脏读等操作。
四个原则
  • 一致性(Consistency)
  • 隔离性(Isolation)
  • 原子性(Atomic)
  • 持续性(Durability)

通过xml文件配置事务

通用配置

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>

切面配置

<!-- 配置切面 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- 配置属性 -->
    <tx:attributes>
        <tx:method name="save" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<!-- aop配置切面 -->
<aop:config>
    <aop:pointcut expression="execution(* com.ben.dao.impl.*.*(..))" id="pointCut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>

通过注解配置事务

首先清除上面的配置,添加一条注解配置

<tx:annotation-driven transaction-manager="transactionManager" />

在dao层中的方法上添加注解

@Transactional

当然注解中也可以配置一些内容(有些参数在最底下看,查找)

配置注意
  • transactionManager的配置若为org.springframework.orm.hibernate4.HibernateTransactionManager
  • sessionFactory的配置就得为org.springframework.orm.hibernate4.LocalSessionFactoryBean
  • 如果是hibernate5的话,也要做对应的匹配
  • 如果是hibernate3的话,sessionFactory配置org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean(注解配置)
  • 如果出现hibernate3不能转成hibernate4的错误的话,请引入这个包spring-orm-4.3.6.RELEASE.jar

其它内容

xml配置的事务参数

  • PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
  • PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
  • PROPAGATION_MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
  • PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
  • PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
  • PROPAGATION_NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。

注解配置事务的参数

  • @Transactional(propagation=Propagation.REQUIRED) 如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)
  • @Transactional(propagation=Propagation.NOT_SUPPORTED) 容器不为这个方法开启事务
  • @Transactional(propagation=Propagation.REQUIRES_NEW) 不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
  • @Transactional(propagation=Propagation.MANDATORY) 必须在一个已有的事务中执行,否则抛出异常
  • @Transactional(propagation=Propagation.NEVER) 必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
  • @Transactional(propagation=Propagation.SUPPORTS) 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.

注解timeout

  • @Transactional(timeout=30) //默认是30秒

注解的事务隔离级别

  • @Transactional(isolation = Isolation.READ_UNCOMMITTED) 读取未提交数据(会出现脏读, 不可重复读) 基本不使用
  • @Transactional(isolation = Isolation.READ_COMMITTED) 读取已提交数据(会出现不可重复读和幻读)
  • @Transactional(isolation = Isolation.REPEATABLE_READ) 可重复读(会出现幻读)
  • @Transactional(isolation = Isolation.SERIALIZABLE) 串行化

数据库创建事务解决的几种问题

  • 脏读 : 一个事务读取到另一事务未提交的更新数据
  • 不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说, 后续读取可以读到另一事务已提交的更新数据. 相反, "可重复读"在同一事务中多次读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据
  • 幻读 : 一个事务读到另一个事务已提交的insert数据

相关文章

网友评论

      本文标题:Spring的aop配置和简单事务配置

      本文链接:https://www.haomeiwen.com/subject/iknsyftx.html