SpringAOP结合事务切入目标对象

  作者:记性不好的阁主

环境依赖


spring基础包
 commons-logging-1.1.3.jar
 spring-beans-4.0.0.RELEASE.jar
 spring-context-4.0.0.RELEASE.jar
 spring-core-4.0.0.RELEASE.jar
 spring-expression-4.0.0.RELEASE.jar
面向切面包
 spring-aop-4.0.0.RELEASE.jar
 spring-aspects-4.0.0.RELEASE.jar
加强版面向切面包
 com.springsource.net.sf.cglib-2.2.0.jar
 com.springsource.org.aopalliance-1.0.0.jar
 com.springsource.org.aspectj.weaver-1.6.4.RELEASE.jar
数据库连接和事务相关包
c3p0-0.9.5.3.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.34.jar
spring-jdbc-4.0.0.RELEASE-sources.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar


学生的增删日志例


1、定义接口


public interface StudentServiceInterface {
// boolean addStudent(Student student);
// boolean deleteStudent(Student student);
    void addStudent(Student student);
    void deleteStudent(Student student);
}


2、定义实现类


@Service
public class StudentService implements StudentServiceInterface {

    StudentDao studentDao;

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

//有返回值
// //将需要成为事务的方法前增加注解
// @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
// @Override
// public boolean addStudent(Student student) {
// if(true){
// studentDao.addStudent(student);
// //System.out.println(1/0); 异常测试
// return true;
// }
// return false;
// }
// //将需要成为事务的方法前增加注解
// @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
// @Override
// public boolean deleteStudent(Student student) {
// if(true){
// studentDao.deleteStudent(student);
// return true;
// }
// return false;
// }


    //无返回值
    //将需要成为事务的方法前增加注解
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    @Override
    public void addStudent(Student student) {
        if(true){
            studentDao.addStudent(student);
            //System.out.println(1/0); 异常测试
        }

    }
    //将需要成为事务的方法前增加注解
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    @Override
    public void deleteStudent(Student student) {
        if(true){
            studentDao.deleteStudent(student);
        }
    }




}


3、定义切面类


@Aspect  //表明此类是一个切面
@Component
public class LogUtils {

    //想在执行目标方法之前
    //写切入点表达式 execution(访问权限符 返回值类型 方法签名)
    @Before('execution(public * com.laoxu.Service.StudentService.*(com.laoxu.Bean.Student))') //*表示所有方法
    public static void LogStart(JoinPoint jp){
        System.out.println('@Before(方法执行之前)目标对象:【'+ jp.getTarget() +'】' +
                '----' +
                '【'+ jp.getSignature().getName() +'】方法开始执行'+
                '----'+
                '参数列表'+
                '【'+ Arrays.toString(jp.getArgs()) +'】'

        );
    }

    //想在目标方法结束之后执行
    @After('execution(public * com.laoxu.Service.StudentService.*(com.laoxu.Bean.Student))')
    public static void End(JoinPoint jp){
        System.out.println('@After(方法执行完毕)目标对象:【'+ jp.getTarget() +'】' +
                '----' +
                '【'+ jp.getSignature().getName() +'】方法开始执行'+
                '----'+
                '参数列表'+
                '【'+ Arrays.toString(jp.getArgs()) +'】'
        );
    }

    //想在目标方法正常执行之后
    @AfterReturning(pointcut = 'execution(public * com.laoxu.Service.StudentService.*(com.laoxu.Bean.Student))',returning = 'returningValue')
    public static void LogReturn(JoinPoint jp,Object returningValue){
        System.out.println('@AfterReturning(方法正常执行返回了)目标对象:【'+ jp.getTarget() +'】' +
                '----' +
                '【'+ jp.getSignature().getName() +'】方法正常执行'+
                '----'+
                '参数列表'+
                '【'+ Arrays.toString(jp.getArgs()) +'】'+
                '----'+
                '返回值:'+
                '【'+ returningValue +'】'

        );
        System.out.println();
    }
    //想在目标方法异常之后执行
    @AfterThrowing(pointcut = 'execution(public * com.laoxu.Service.StudentService.*(com.laoxu.Bean.Student))',throwing = 'Exception')
    public static void LogException(JoinPoint jp,Throwable Exception){
        System.out.println('@AfterThrowing【'+ jp.getSignature().getName() +'】方法出现异常,异常信息是:'+Exception);
    }



    //环绕通知 参数ProceedingJoinPoint jp
    @Around('execution(public * com.laoxu.Service.StudentService.*(com.laoxu.Bean.Student))')
    public static void LogAround(ProceedingJoinPoint jp){
        //方法执行之前:前置通知
        System.out.println('【环绕】方法执行之前:前置通知');
        try {
            //方法执行时
            jp.proceed(); //执行方法
            //方法执行之后:后置通知
            System.out.println('【环绕】方法执行之后:后置通知');
        }catch (Throwable e){
            //方法发生异常时:异常通知
            System.out.println('【环绕】方法发生异常时:异常通知');
        }finally {
            //最终通知
            System.out.println('【环绕】最终通知');
        }
    }

}



4、配置SpringIOC容器


<!--    扫描包下的注解(Component Controller Service Repository)-->
        <context:component-scan base-package='com.laoxu'></context:component-scan>

<!-- 开启注解对AOP的支持-->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>


<!-- 配置数据库相关-->
        <bean id='dataSource' class='com.mchange.v2.c3p0.ComboPooledDataSource'>
                <property name='user' value='root'></property>
                <property name='password' value='root'></property>
                <property name='jdbcUrl' value='jdbc:mysql://127.0.0.1:3306/sorm?useUnicode=true&amp;characterEncoding=utf-8'></property>
                <property name='driverClass' value='com.mysql.jdbc.Driver'></property>
        </bean>




<!-- 配置事务管理器txManager-->
        <bean id='txManager' class='org.springframework.jdbc.datasource.DataSourceTransactionManager'>
                <property name='dataSource' ref='dataSource'></property>
        </bean>


<!-- 增加对事务的支持-->
<!-- transaction-manager事务管理器-->
        <tx:annotation-driven transaction-manager='txManager'/>


5、测试


public class Test {
    private static ApplicationContext ioc = new ClassPathXmlApplicationContext('applicationContext.xml');

    public static void main(String[] args) {
        StudentServiceInterface ss = ioc.getBean(StudentServiceInterface.class);
        Student stu1 = new Student();
        ss.addStudent(stu1);
        ss.deleteStudent(stu1);
    }
}


相关推荐

评论 抢沙发

表情

分类选择