您现在的位置是:首页 > 个人日记个人日记
spring-09-AOP-注解配置详细介绍
2019-02-03 18:48:59【个人日记】418人已围观
简介使用注解的方式来配置AOP更加简洁
注解配置
先在spring-config.xml加入注解扫描
<?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:contet="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"><!--扫描注解--><contet:component-scan base-package="com.spring"></contet:component-scan><!--使AOP注解生效如果要代理的类有接口,且实现则使用JDK的动态代理如果要代理的类没有实现接口则使用cglib动态代理--><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
在service层加入注解@Service
主要配置在增强中
package com.spring.aspect;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;@Component@Aspect//表示一个切面public class TransactionAdvice {/*** 切入点配置*///这里使用切入点@Pointcut("execution(* com.spring.service.UserService.*(*))")private void pointCut() {}/*** 使用环绕** @param proceedingJoinPoint* @return*/// @Around("pointCut()")public Object around(ProceedingJoinPoint proceedingJoinPoint) {Object result = null;try {System.out.println("开启事务");result = proceedingJoinPoint.proceed();System.out.println("提交事务");} catch (Throwable throwable) {result = 500;System.out.println("回滚事务");throwable.printStackTrace();} finally {System.out.println("释放资源");}return result;}/*** 前置通知*/@Before("pointCut()")public void brfore() {System.out.println("开启事务");}/*** 后置通知*/@AfterReturning("pointCut()")public void afterReturning() {System.out.println("提交事务");}/*** 最终停止*/@After("pointCut()")public void after() {System.out.println("释放资源");}/*** 异常通知*/@AfterThrowing(pointcut = "pointCut()",throwing = "e")public void afterThrowing(Throwable e) {System.out.println("回滚事务" + e.getMessage());}}
以上是两种方式配置AOP
1) 直接使用@Around标签环绕
2) 在创建之前需要在类中创建一个名称为切点名称的方法,设为私有,并在上面使用注解 @Pointcut("execution(* com.spring.service.UserService.())")
Tags: JavaWeb
上一篇: mybatis-03-Mapper代理
下一篇: mybatis-09-缓存
相关文章
随机图文
评论区
2025-11-09 04:27:57
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信
