JAVA编程120——SpringAOP原理

一、AOP(Aspect Oriented Programming)原理解析

1、概念:面向切面编程
2、理解:在不改变主线代码的情况下添加一些支线业务代码
3、应用:1、添加支线业务。2、类方法功能增强。

在这里插入图片描述

4、SpringAOP配置
<?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:context="http://www.springframework.org/schema/context"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置QueryRunner对象-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"></bean>

    <!--配置数据访问层对象-->
    <bean id="accountDao" class="com.mollen.dao.impl.AccountDaoImpl">
        <property name="queryRunner" ref="queryRunner"></property>
    </bean>

    <!--配置Spring的AOP-->
    <!--真实对象/目标对象-->
    <bean id="accountService" class="com.mollen.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--增强类-->
    <bean id="transactionManger" class="com.mollen.utils.TransactionManger"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="txAspect" ref="transactionManger">
            <aop:pointcut id="txPointcut" expression="execution(* com.mollen.service.impl.AccountServiceImpl.transfer(..))"></aop:pointcut>
            <!--配置通知-->
            <!--前置通知:开启事物-->
            <aop:before method="startTransaction" pointcut-ref="txPointcut"></aop:before>
            <!--后置通知,提交事物-->
            <aop:after-returning method="commitTransaction" pointcut-ref="txPointcut"></aop:after-returning>
            <!--异常通知,回滚事物-->
            <aop:after-throwing method="rollbackTransaction" pointcut-ref="txPointcut"></aop:after-throwing>
            <!--最终通知,是否资源-->
            <aop:after method="release" pointcut-ref="txPointcut"></aop:after>
        </aop:aspect>
    </aop:config>

</beans>

猜你喜欢

转载自blog.csdn.net/mollen/article/details/83856230