1.maven配置 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <
1.maven配置
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency><dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency></dependencies>
2.新建TestAspect类
@Component@Aspectpublic class TestAspect { public TestAspect() { System.out.println("创建TestAspect成功"); } //定义切点 @Pointcut("execution(* *.saying(..))") public void say(){}//环绕通知。 @Around("say()") public void sayAround(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("环绕通知开始"); pjp.proceed();//执行方法 System.out.println("环绕通知结束"); } @Before("say()") public void sayBeFore(JoinPoint joinPoint) { System.out.println("sayBeFore"); System.out.println("获取连接点方法运行时的入参列表:"+joinPoint.getArgs()); System.out.println("获取连接点的方法签名对象:"+joinPoint.getSignature()); System.out.println("获取连接点所在的目标对象:"+joinPoint.getTarget()); } @After("say()") public void sayAfter(JoinPoint joinPoint) { System.out.println("sayAfter"); }}
4.新建TestSayService
@Servicepublic class TestSayService { public void saying(String src) { System.out.println("saying:"+src); }}
5.新建Test
@Componentpublic class Test { @Autowired TestSayService testSay; @PostConstruct public void init() { testSay.saying("hello spingboot aop"); }}
6.新建SpringbootAopApplication
@SpringBootApplicationpublic class SpringbootAopApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAopApplication.class, args); }}
7.启动springboot,显示:
创建TestAspect成功
环绕通知开始
sayBeFore
获取连接点方法运行时的入参列表:[Ljava.lang.Object;@2740e316
获取连接点的方法签名对象:void com.test.TestSayService.saying(String)
获取连接点所在的目标对象:com.test.TestSayService@5d342959
saying:hello spingboot aop
环绕通知结束
sayAfter