注解方式实现AOP切面编程

需要引入的依赖,maven配置:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.12</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.12</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
</dependencies>

spring-config配置:

<span style="color:#330033;"><?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-3.1.xsd
        http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:component-scan base-package="com.along.apple" use-default-filters="true">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 通过aop命名空间的<aop:aspectj-autoproxy/>声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面-->
 </span><span style="color:#ff0000;">   <aop:aspectj-autoproxy /></span><span style="color:#330033;">

    <bean id="apple" class="com.along.apple.aop.Apple"/>
</beans></span>
特别需要注意,注解方式实现的AOP在配置文件中一定要添加<aop:aspectj-autoproxy />否则注解不起作用,切面无法织入目标对象,原因是该配置标示等同于引入AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,并完成创建代理织入切面的工作。 

AOP注入的目标类:

@Service
public class Apple {


    /**
     *
     * @param appleName
     */
    public void addApple(String appleName){
        System.out.println("加入一个苹果:"+appleName);

    }

    /**
     *
     * @param appleName
     */
    public void  deleteApple(String appleName){
        System.out.println("删除一个苹果"+appleName);
    }

    /**
     *
     * @param appleName
     */
    public void editAppple(String appleName){
        System.out.println("修改一个苹果的属性"+appleName);
    }



}

简单AOP切面实现:

@Component
@Aspect
public class SimpleAspect {

    public static final String ASPECT_SERVICE_EXCUTION = "execution(* com.along.apple.aop..*.*(..))";

    /**
     * 切点表达式,方便书写,不实现任何内容
     * 也可没有该方法,直接写切点
     */
    @Pointcut(ASPECT_SERVICE_EXCUTION)
    public void MyPointCut() {

    }

    @After("MyPointCut()")
    public void after(JoinPoint joinPoint) {
        System.out.println("后置通知after aspect executed.........");
    }

    @Before("MyPointCut()")
    public void before(JoinPoint joinPoint) {
        //如果需要这里可以取出参数进行处理
        Object[] args = joinPoint.getArgs();
        System.out.println("连接点信息" + joinPoint.getThis()
                + "目标对象"+ joinPoint.getTarget()
                + "当前连接点签名"+ joinPoint.getSignature()
                + "连接点方法所在类文件中的位置" + joinPoint.getSourceLocation());
        System.out.println("前置通知before aspect executing");
    }

    @AfterReturning(pointcut = "MyPointCut()", returning = "returnVal")
    public void afterReturning(JoinPoint joinPoint, Object returnVal) {
        System.out.println("返回后通知afterReturning executed, return result is "
                + returnVal);
    }

    @Around("MyPointCut()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前处理通知around start..");
        try {
            pjp.proceed();
        } catch (Throwable ex) {
            System.out.println("error in around");
            throw ex;
        }
        System.out.println("环绕后处理通知around end");
    }

    @AfterThrowing(pointcut = "MyPointCut()", throwing = "error")
    public void afterThrowing(JoinPoint jp, Throwable error) {
        System.out.println("异常通知error:" + error);
    }
}

入口类:

public class AopTest {
    
    public static  void main(String[] args){
        ApplicationContext  context = new ClassPathXmlApplicationContext("spring-config*.xml");

        Apple apple =(Apple)context.getBean("apple");
        apple.addApple("红苹果");
        
    }

}

运行结果如下图,可以比较几种通知的通知顺序:

环绕前处理通知around start..
连接点信息....
前置通知before aspect executing
加入一个苹果:红苹果
环绕后处理通知around end
后置通知after aspect executed.........
返回后通知afterReturning executed, return result is null



  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值