AOP实现方式一

1.创建相应的类

image

2.代码

service沿用前面的
增加两个log
Log.java

package com.shao.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    //Method:受执行的目标对象的方法
    //objects: 参数
    //o:目标对象
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        assert o != null;
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

AfterLog.java

package com.shao.log;

import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

    //执行之后拿回了返回值
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+", 返回了"+o);
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

    <bean id="userService" class="com.shao.service.UserServiceImpl"/>
    <bean id="log" class="com.shao.log.Log"/>
    <bean id="afterLog" class="com.shao.log.AfterLog"/>

    <!--配置Aop:导入AOP约束-->
    <aop:config>
        <!--切入点:expression表达式:要执行的位置-->
        <!--这个类的所有方法-->
        <aop:pointcut id="pointcut" expression="execution(* com.shao.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <!--把log这个类切入到这个方法中去-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

3.测试

import com.shao.service.UserService;
import com.shao.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    @org.junit.Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //一定要注意:动态代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

posted @ 2021-10-26 09:38  蘑菇王国大聪明  阅读(43)  评论(0)    收藏  举报