Spring基于注解实现AOP

xml配置。编写接口方法,和实现类,把配置类和实现类放进IOC容器中

 

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

    <!--注册bean-->
    <bean id="userservice" class="com.zj.service.UserServiceImpl"></bean>
    <bean id="pointcut" class="com.zj.aop.DiyPointcut"/>


    <bean id="annotationPointcut" class="com.zj.aop.AnnoPointCut"/>
    <aop:aspectj-autoproxy/>
    <!--aop的配置-->

<!--    <aop:config>-->

<!--        <aop:aspect ref="pointcut">-->
<!--            <aop:pointcut id="diyPointcut" expression="execution(* com.zj.service.UserServiceImpl.*(..))"/>-->
<!--            <aop:before method="before" pointcut-ref="diyPointcut"/>-->
<!--            <aop:after method="after" pointcut-ref="diyPointcut"/>-->
<!--        </aop:aspect>-->
<!--    </aop:config>-->

</beans>

编写具体的配置类

package com.zj.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnoPointCut {

    @Before("execution(* com.zj.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }

    @After("execution(* com.zj.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }

    @Around("execution(* com.zj.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法proceed
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

 

代码执行结果:

 

posted @ 2021-01-20 13:57  程序练习生1412  阅读(48)  评论(0)    收藏  举报