如何在项目中使用AOP

2017-12-28  本文已影响0人  不将就51y

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());

    }
}
@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 注解方式配置

上一篇 下一篇

猜你喜欢

热点阅读