spring-aop实现方式

详解:在引入AOP模块之后,一般来讲,不用去做其他配置。spring.aop.auto属性默认是开启的,也就是说只要引入了AOP的依赖之后,默认已经增加了@EnableAspectJAutoProxy

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-aopartifactId>
dependency>

方法1:实现接口

@Configuration
public class ServiceAspectJExpressionPointcutAdvisor extends AspectJExpressionPointcutAdvisor {

    @PostConstruct
    public void init() {
        this.setExpression("execution(public * com.example.demo.service.impl.*.*(..))");
        this.setAdvice(new ServiceMethodInterceptor());
    }
}
public class ServiceMethodInterceptor implements MethodInterceptor {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Long start = System.currentTimeMillis();
        Object proceed = methodInvocation.proceed();
        log.info("消耗时间:{}" , System.currentTimeMillis() - start);
        return proceed;
    }
}

方法2:注解方式

@Aspect
@Component
public class LogAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.example.demo.service.impl.*.*(..))")
    public void operationLog(){}

    @Around("operationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        log.info("注解版,消耗时间:{}" , System.currentTimeMillis() - start);
        return proceed;
    }
}

你可能感兴趣的:(aop,spring,spring)