- 创建目标类
首先,创建一个简单的服务类,该类包含一些业务方法。
| package com.powernode.spring6.service2; |
| |
| public class MyService { |
| public void doSomething() { |
| System.out.println("Doing something in MyService..."); |
| } |
| |
| public String doSomethingElse(String input) { |
| System.out.println("Doing something else in MyService with input: " + input); |
| return "World " + input; |
| } |
| } |
| package com.powernode.spring6.service2; |
| |
| import org.aspectj.lang.JoinPoint; |
| import org.aspectj.lang.ProceedingJoinPoint; |
| |
| public class JournalAspect { |
| |
| public void beforeAdvice(JoinPoint joinPoint) { |
| System.out.println("Before method: " + joinPoint.getSignature().getName()); |
| } |
| |
| |
| public void afterAdvice(JoinPoint joinPoint) { |
| System.out.println("After method: " + joinPoint.getSignature().getName()); |
| } |
| |
| |
| public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { |
| System.out.println("Entering method: " + proceedingJoinPoint.getSignature().getName()); |
| Object result = proceedingJoinPoint.proceed(); |
| System.out.println("Exiting method: " + proceedingJoinPoint.getSignature().getName()); |
| return result; |
| } |
| } |
| <?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: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> |
| |
| |
| |
| <bean id="myService" class="com.powernode.spring6.service2.MyService"/> |
| |
| |
| <bean id="journalAspect" class="com.powernode.spring6.service2.JournalAspect"/> |
| |
| |
| <aop:config> |
| |
| <aop:pointcut id="serviceMethods" expression="execution(* com.powernode.spring6.service2.*.*(..))"/> |
| |
| |
| <aop:aspect ref="journalAspect"> |
| <aop:around method="aroundAdvice" pointcut-ref="serviceMethods"/> |
| </aop:aspect> |
| </aop:config> |
| @Test |
| public void aspectTest(){ |
| ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-aspect.xml"); |
| MyService myService = classPathXmlApplicationContext.getBean("myService", MyService.class); |
| |
| String 你好 = myService.doSomethingElse("你好"); |
| System.out.println(你好); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具