基于注解的AOP开发
1. 创建接口和目标类(内部有切点)
package com.sjj.anno;
public interface TargetInterface {
public void print_hello();
}
package com.sjj.anno;
import org.springframework.stereotype.Component;
@Component("target")
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")
public class MyAspect {
@Before("execution(* com.sjj.anno.*.*(..))")
public void before(){
System.out.println("=====前置增强=====");
}
}
3. 将目标类和切面类的对象创建权交给spring
4. 在切面类中使用注解配置织入关系
5. 在配置文件中开启组件扫描和AOP自动代理
<context:component-scan base-package="com.sjj.anno" />
<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 |
最终通知,无论是否有异常都执行 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix