S++

千线一眼

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Spring-注解实现AOP

基于注解的AOP开发

1. 创建接口和目标类(内部有切点)

package com.sjj.anno;

public interface TargetInterface {
    public void print_hello();
}
package com.sjj.anno;

import org.springframework.stereotype.Component;

@Component("target") // 交予spring
public class Target implements TargetInterface {
    @Override
    public void print_hello() {
        System.out.println("HHHHHello");
    }
}

2. 创建切面类(内部有增强方法)

package com.sjj.anno;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect // 声明切面类
@Component("myAspect") // 交予spring
public class MyAspect {
    @Before("execution(* com.sjj.anno.*.*(..))")
    public void before(){
        System.out.println("=====前置增强=====");
    }
}

3. 将目标类和切面类的对象创建权交给spring

// Component注解

4. 在切面类中使用注解配置织入关系

// Aspect注解和通知方法注解(Before之类的)

5. 在配置文件中开启组件扫描和AOP自动代理

    <!--组件扫描-->
    <context:component-scan base-package="com.sjj.anno" />
    <!--aop自动代理-->
    <aop:aspectj-autoproxy/>

6. 测试

package com.sjj.anno;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:appContext-anno.xml")
public class AnnoTest {
    @Autowired
    private TargetInterface target;

    @Test
    public void test_anno01(){
        target.print_hello();
    }
}

注解解析

注解通知的类型

名称 注解 说明
前置 @Before 切入点方法之前
后置 @AfterReturning 切入点方法之后
环绕 @Around 切入点方法前后都执行
异常抛出 @Throwing 出现异常时执行
最终 @After 最终通知,无论是否有异常都执行

posted on   S++  阅读(37)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示