spring的学习____8 spring_AoP的实现方式一:使用spring API实现

(本案例是 idea下的maven项目)

1.UserService(接口的编写):

public interface UserService {

    void add();
    void delete();
    void update();
    void query();
}

2.UserServiceImpl(接口实现类)的编写:

public class UserServiceImpl implements UserService {


    public void add() {
        System.out.println("增加一个用户!");
    }

    public void delete() {
        System.out.println("删除一个用户!");
    }

    public void update() {
        System.out.println("修改一个用户!");
    }

    public void query() {
        System.out.println("查询一个用户!");
    }
}

3.定义日志增加类的实现:

//通过spring api实现 aop
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"  执行了"+method.getName());
    }
}
//通过spring api实现
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println(o1.getClass().getName()+" 执行了"+method.getName()+"  返回值为:"+o);
    }
}

4.Spring 核心配置文件的编写(applicationContext.xml)的编写:

<?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.kuang.service.UserServiceImpl"/>

    <!--注册日志类的bean-->
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>

    <!--使用spring的aop切入
    1.导入约束:
        xmlns:aop="http://www.springframework.org/schema/aop"
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
    2.aop:config


    -->
    <aop:config>
        <!--切入点
        expression 表达式,表示要切入的位置
        语法:execution([类的修饰符] [类的全路径] [方法] [参数])
        -->
        <aop:pointcut id="pointcut" expression
                ="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
        <!--执行通知,增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>


</beans>

5.测试类的编写:(注意获取Bean对象使用 接口 来接收的)

public class Test {

    @org.junit.Test
    public void test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userImpl = (UserService)context.getBean("userImpl");

        userImpl.add();

    }
}

总结:

使用Spring 的Aop方式向原来接口的实现方法中横向织入了日志信息(通过实现接口: MethodBeforeAdvice,AfterReturningAdvice)的方式实现了Aop的横向织入。

 

posted @ 2019-07-30 20:54  德鲁大叔817  阅读(262)  评论(0编辑  收藏  举报