spring基础aop切面编程注解@配置方式

68 篇文章 0 订阅

新建maven项目

 导入依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>

UserDao.java

package com.shrimpking.aspectj;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/5 16:06
 */
public interface UserDao
{
    public void addUser();

    public void deleteUser();
}

UserDaoImpl.java

package com.shrimpking.aspectj;

import org.springframework.stereotype.Repository;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/5 16:07
 */
@Repository
public class UserDaoImpl implements UserDao
{
    @Override
    public void addUser()
    {
        System.out.println("添加用户");
    }

    @Override
    public void deleteUser()
    {
        System.out.println("删除用户");
    }
}

MyAspect.java

package com.shrimpking.aspectj.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/5 16:08
 */
@Aspect
@Component
public class MyAspect
{
    //切入点
    @Pointcut("execution(* com.shrimpking.aspectj.*.*(..))")
    public void myPointCut(){}

    //前置通知
    @Before("myPointCut()")
    public void myBefore(JoinPoint joinPoint)
    {
        System.out.println("前置通知,模拟权限检查...");
        System.out.println("目标类是," + joinPoint.getTarget());
        System.out.println("被植入增强的目标方法是," + joinPoint.getSignature().getName());
    }

    //后置通知
    @AfterReturning(value = "myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint)
    {
        System.out.println("后置通知,模拟日志记录...");
        System.out.println("被植入增强的目标方法是," + joinPoint.getSignature().getName());
    }

    //环绕通知
    @Around("myPointCut()")
    public void myAround(ProceedingJoinPoint joinPoint) throws Throwable
    {
        System.out.println("环绕通知开始,执行目标方法之前,模拟开启事务...");
        joinPoint.proceed();
        System.out.println("环绕通知结束,执行目标方法之后,模拟关闭事务...");
    }

    //异常通知
    @AfterThrowing(value = "myPointCut()",throwing = "e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e)
    {
        System.out.println("异常通知,出错了" + e.getMessage());
    }

    //最终通知
    @After("myPointCut()")
    public void myAfter()
    {
        System.out.println("最终通知,模拟方法结束后释放资源...");
    }
}

applicationContext.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: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">

    <!-- 包扫描   -->
    <context:component-scan base-package="com.shrimpking.aspectj"/>
    <!-- 启动基于注解的声明式aspect支持   -->
    <aop:aspectj-autoproxy/>
</beans>

AnnotationTest.java

import com.shrimpking.aspectj.UserDao;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/5 16:31
 */
public class AnnotationTest
{
    @Test
    public void test()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = context.getBean("userDaoImpl", UserDao.class);
        userDao.addUser();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
AOP(面向切面编程)中,注解方式是一种常见的实现方式,可以用于声明切面和通知。在Spring框架中使用注解方式实现AOP可以更加简洁和便捷。 要使用AOP注解方式,首先需要在Spring配置文件中启用AspectJ自动代理,通过在配置文件中添加`<aop:aspectj-autoproxy></aop:aspectj-autoproxy>`来实现。 接下来,可以使用以下注解来实现AOP切面编程: 1. `@Aspect`:用于声明一个类为切面类。 2. `@Pointcut`:用于声明一个切入点,切入点定义了何时何地应该执行切面的通知方法。 3. `@Before`:在目标方法执行之前执行通知。 4. `@After`:在目标方法执行之后(无论是否发生异常)执行通知。 5. `@AfterReturning`:在目标方法执行后返回结果时执行通知。 6. `@AfterThrowing`:在目标方法抛出异常时执行通知。 7. `@Around`:在目标方法执行前后执行通知。 下面是一个使用注解方式实现AOP的示例代码: ```java @Aspect public class LoggingAspect { @Pointcut("execution(* com.example.service.*.*(..))") private void serviceMethods() {} @Before("serviceMethods()") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("Before advice: " + joinPoint.getSignature().getName()); } @After("serviceMethods()") public void afterAdvice(JoinPoint joinPoint) { System.out.println("After advice: " + joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "serviceMethods()", returning = "result") public void afterReturningAdvice(JoinPoint joinPoint, Object result) { System.out.println("After returning advice: " + joinPoint.getSignature().getName() + ", result: " + result); } @AfterThrowing(pointcut = "serviceMethods()", throwing = "exception") public void afterThrowingAdvice(JoinPoint joinPoint, Exception exception) { System.out.println("After throwing advice: " + joinPoint.getSignature().getName() + ", exception: " + exception.getMessage()); } @Around("serviceMethods()") public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before around advice: " + joinPoint.getSignature().getName()); Object result = joinPoint.proceed(); System.out.println("After around advice: " + joinPoint.getSignature().getName()); return result; } } ``` 在上面的示例中,`LoggingAspect`类使用了`@Aspect`注解声明为切面类,然后通过`@Pointcut`注解定义了一个切入点`serviceMethods()`,它匹配了`com.example.service`包下的所有方法。 接着,使用各种不同的注解来实现不同类型的通知,比如`@Before`、`@After`、`@AfterReturning`、`@AfterThrowing`和`@Around`,并在这些通知方法中实现相应的逻辑。 以上就是使用注解方式实现AOP切面编程的简要介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值