美文网首页
如何在项目中使用AOP

如何在项目中使用AOP

作者: 不将就51y | 来源:发表于2017-12-28 18:47 被阅读0次

1、Spring配置文件中增加aop相关配置

<?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:context="http://www.springframework.org/schema/context"
    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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <context:component-scan base-package="com.test.demo.xxx"></context:component-scan>

</beans>

2、注解AOP

package me.laiyijie.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;

@Service
@Aspect
public class TimeMonitor {

    @Around("execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))")
    public void monitorAround(ProceedingJoinPoint pjp) throws Throwable {

        System.out.println("method start time:" + System.currentTimeMillis());

        Object re = pjp.proceed();

        System.out.println("method end time:" + System.currentTimeMillis());

    }
}
  • 类有两个注释,分别是@Service和@Aspect,第一个注解是使得TimeMonitor受Spring托管并实例化。@Aspect就是使得这个类具有AOP功能(你可以这样理解)两个注解缺一不可
@Around(“execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))”)
  • @Around表示包围一个函数,也就是可以在函数执行前做一些事情,也可以在函数执行后做一些事情
    execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..)) 这个比较好理解,就是使用表达式的方式指定了要对哪个函数进行包围!

3、spring配置文件中配置切面代替注解

<aop:config>
        <aop:aspect id="myAop" ref="controllerAop">
            <aop:pointcut id="target"
                          expression="execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))" />
            <aop:around method="monitorAround" pointcut-ref="target" />
        </aop:aspect>
    </aop:config>

参考文章
Spring Aop实例(AOP 如此简单)@Aspect、@Around 注解方式配置

相关文章

网友评论

      本文标题:如何在项目中使用AOP

      本文链接:https://www.haomeiwen.com/subject/nqbvgxtx.html