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得到当前的代理对象,更一步得到一些方法签名,方法的参数等一些具体信息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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