前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring的AOP切面编程

Spring的AOP切面编程

作者头像
CBeann
发布2023-12-25 16:16:03
1230
发布2023-12-25 16:16:03
举报
文章被收录于专栏:CBeann的博客CBeann的博客

语言苍白无力,我们直接代码说话

代码语言:javascript
复制
package com.example.demo.aspect;
import org.springframework.stereotype.Component;
@Component
public class AtithmeticCalulator {
	
	public int add(int a,int b){
		return a+b;
	}
	
	public int sub(int a,int b){
		return a-b;
	}
	
	public int mul(int a,int b){
		return a*b;
	}
	
	public int div(int a,int b){
		return a/b;
	}

}

这是一个类,以方法add为例,当我们想在每一个方面前面添加一个告诉自己方法名和参数的时候,你会怎么写?

代码语言:javascript
复制
	public int add(int a,int b){
		System.out.println("method mane:add    参数["+a+","+b+"]");
		return a+b;
	}

有没有感觉很麻烦,如果我四个方法都要用,你就要写4遍

这个时候AOP派上用场

代码语言:javascript
复制
package com.example.demo.aspect;  
  
import java.util.Arrays;  
import java.util.List;  
  
import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.After;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.springframework.stereotype.Component;  
  
@Component//将组件加载到ioc容器,必须写,否则加载不到ioc容器  
@Aspect//告诉ioc容器这是一个切面类,里面有切面方法  
public class MyAspect {  
  
    //切面表达式public int com.example.demo.aspect.AtithmeticCalulator.*(int,int)  
    //包com.example.demo.aspect下的AtithmeticCalulator类所是public ,返回值是int,参数是(int,int)的方法  
    @Before("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")
    public void before(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is begin:"+args);  
    }  
      
      
    @After("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")  
    public void after(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is close:"+args);  
    }  
      
      
  
}  

运行结果所示:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 语言苍白无力,我们直接代码说话
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档