Spring AOP(面向切面)实例及步骤

Spring AOP(面向切面)实例及步骤

重要概念
切面
切面就是在程序中抽象出来的一个个通用的功能的类。比如:日志、事务、异常处理、性能监控、统计。
连接点
连接点就是对植入通过功能的地方的一个封装。就是切面中发放的输入参数。
通知
通知就是切面类当中具体事项功能的方法
切入点
切入点就是需要添加切面功能的地方,是消息执行的地方。
来一个示例:
1、建一个java项目
2、导入jar包并且buildPath
3、编写spring配置文件(applicationContext.xml)
eg:

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
    <!-- <bean id="menuService" class="com.linksky.daoImpl.MenuService"></bean> -->
    <bean id="UserService" class="com.linksky.service.UserService">
        <property name="userdao" ref="sqlserverDao"></property>
    </bean>
    <bean id="sqlserverDao" class="com.linksky.daoImpl.SqlServerUserDao"></bean>
    <bean id="mysqlDao" class="com.linksky.daoImpl.MysqlUserDao"></bean>
</beans>

4、编写切面类,并且进行相应配置
eg:

<!-- 在Spring当中声明切面 -->
    <bean id="log" class="com.linksky.aspect.LogAspect"></bean>
    <!-- 配置aspect作为动态代理的实现 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!-- 配置Aop -->
    <aop:config>
        <!-- 切点配置 -->
        <aop:pointcut expression="execution(* com.linksky.service.*.*(..))" id="logPointCut"/>
        <!-- 切面配置 -->
        <aop:aspect id="logAspect" ref="log">
            <aop:before method="log" pointcut-ref="logPointCut"/>
        </aop:aspect>
    </aop:config>

5、编写测试类进行测试
通知详解
切面中的方法就叫通知。
通知分为前置通知、后置通知、异常通知、最终通知、环绕通知。
前置通知(Before)
在目标方法之前执行。
配置eg:

<!-- 切面配置 -->
        <aop:aspect id="logAspect" ref="log">
            <!-- 通知,通知策略 -->
            <aop:before method="log" pointcut-ref="logPointCut"/>
        </aop:aspect>

后置通知(after-reruning)
在结果成功返回之后执行。后置通知可以获取目标方法的返回值。
配置eg:

<aop:after-returning method="afterLog" pointcut-ref="logPointCut" returning="result"/>

必须注意后面的returning。。。。要写返回值!

异常通知(after-throwing)
在程序抛出异常之后执行
配置eg:

<aop:aspect id="logAspect" ref="log">
            <!-- 通知,通知策略 -->
            <aop:after-throwing method="exceptionLog" pointcut-ref="logPointCut" throwing="e"/>
        </aop:aspect>

最终通知(after)
在方法的最后执行,和前置通知一样,配置简单。
配置eg:

<aop:after method="lastLog" pointcut-ref="logPointCut" />

环绕通知(around)
eg:

<aop:around method="aroundLog" pointcut-ref="logPointCut" />
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值