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" />
本文介绍Spring AOP(面向切面编程)的概念及其在实际项目中的应用。文章详细解释了切面、连接点、通知、切入点等核心概念,并通过一个具体的例子展示了如何使用Spring AOP配置切面、实现前置通知、后置通知、异常通知、最终通知和环绕通知。
933

被折叠的 条评论
为什么被折叠?



