springboot aop

springboot怎样使用aop呢?我们知道aop的实现一种是jdk动态代理实现aop,一种是cglib动态代理实现的aop。

先看一个demo,加入依赖:

<dependencies>
     <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
     </dependency>
</dependencies>

定义一个controller

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/queryUserById/{id}")
    @ResponseBody
    private String queryUserById(@PathVariable int id){
        return userService.queryUserById(id);
    }
}

定义一个service层接口:

public interface UserService {

    String queryUserById(int id);
}

其实现:

@Service("userService")
public class UserServiceImpl implements UserService{

    @Override
    public String queryUserById(int id) {
        return "user home";
    }

}

定义具体的aop功能,封装横切关注点,配置通知等等,怎么在aop中拿到横切的对象。

@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Before("execution(* com.zhihao.miao.service..*.*(..))")
    public void log(){
        //logger.info("before method log done"+ AopContext.currentProxy().getClass());
        logger.info("before method log done");
    }

    //可以通过JoinPoint取到aop的类名,方法参数,方法签名
    @After("execution(* com.zhihao.miao.service..*.*(..))")
    public void logAfter(JoinPoint joinPoint){
        logger.info("after method log done "+joinPoint.getTarget().getClass()+",args="+ Arrays.asList(joinPoint.getArgs())+",method="+joinPoint.getSignature());
    }
}

启动类启动:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

访问:http://localhost:8080/user/queryUserById/1
打印结果,

很简单的实现了aop的功能。

AOP开发流程

  • spring-boot-starter-aop,加入依赖,默认就开启了AOP的支持
  • 写一个Aspect,封装横切关注点(日志,监控等等),需要配置通知(前置通知、后置通知等等)和 切入点(哪些包的哪些类的哪些方法等等)
  • 这个Aspect需要纳入到spring容器管理,并且需要加入@Aspect

深入

可以使用spring.aop.auto配置决定是否启用AOP,默认启用。

AopAutoConfiguration

application.properties配置如下属性,则aop实效,

spring.aop.auto=false

看了AopAutoConfiguration源码发现我们可以指定是JDK的动态代理还是cglib的动态代理,通过设置spring.aop.proxy-target-class这个属性。不设置(默认属性值是false)则默认是jdk的代理。但是如果不设置或者设置为false,但是代理的类没有实现接口的话也是cglib代理。
比如再定义一个类OrderService,并没有实现接口,而上面的UserServiceImpl是实现UserService接口,我们看看其使用了什么动态代理

@Service("orderService")
public class OrderService {

    public String name(){
        return "order home";
    }
}

修改启动类启动,

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        String userServiceClassname = context.getBean("userService").getClass().getName();
        System.out.println("userServiceClassname==="+userServiceClassname);

        String orderServiceclassname = context.getBean("orderService").getClass().getName();
        System.out.println("orderServiceclassname===="+orderServiceclassname);
    }
}

我们看到当spring.aop.proxy-target-class=false(缺省的时候也是false),代理的类如果实现接口那么就使用的是jdk的动态代理,如果没有实现接口那么就使用的是cglib的动态代理。

我们在application.properties中设置spring.aop.proxy-target-class设为true,

spring.aop.proxy-target-class=true

启动启动类,发现二个类都是使用的cglib代理的

图片.png

总结:
默认是使用基于JDK的动态代理来实现AOP,spring.aop.proxy-target-class=false 或者不配置,表示使用JDK的动态代理,pring.aop.proxy-target-class=true表示使用cglib,如果配置了spring.aop.proxy-target-class=false,但是代理类没有实现接口,则依然使用cglib。

拓展

也可以使用
@EnableAspectJAutoProxy(proxyTargetClass=true,exposeProxy=true)这个注解,注解表示启用AOP,当然默认也是启用AOP的,因为springboot的自动装配机制,第一个参数表示是使用JDK的动态代理还是Cglib的代理,第二个参数表示可以使用AopContext这个类进行一些操作。

注释之前所有的application.properties中的配置,在启动类上加上
@EnableAspectJAutoProxy(proxyTargetClass=true,exposeProxy=true)

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true,exposeProxy=true)
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        String userServiceClassname = context.getBean("userService").getClass().getName();
        System.out.println("userServiceClassname==="+userServiceClassname);

        String orderServiceclassname = context.getBean("orderService").getClass().getName();
        System.out.println("orderServiceclassname===="+orderServiceclassname);
    }
}

表示自己启动cglib代理,并且exposeProxy配置为true表示可以横切关注点中使用AopContext这个类,修改一下上面的LogAspect的log方法,

   @Before("execution(* com.zhihao.miao.service..*.*(..))")
    public void log(){
        logger.info("before method log done"+ AopContext.currentProxy().getClass());
        //logger.info("before method log done");
    }

启动并测试,

可以通过AopContext得到当前的代理对象,更一步得到一些方法签名,方法的参数等一些具体信息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,136评论 11 349
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,411评论 1 133
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,678评论 6 342
  • 时光飞逝 转眼间 你我即将分离 各奔东西 也许 我们会离得很远很远 也许 我们不会再见 再也许 我们会忘记彼此 离...
    樱花落ww阅读 215评论 3 2