美文网首页
Java:spring框架(3)AOP面向切面

Java:spring框架(3)AOP面向切面

作者: 梦之志 | 来源:发表于2017-01-11 12:45 被阅读0次

一.创建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 definitions here -->
    <!--配置对象-->
/*
* 1. 配置book对象, 设置id为book
*/
    <bean id="book" class="com.company.Book"></bean>
    <bean id="mybook" class="com.company.Mybook"></bean>

    <aop:config>
        <!--设置切入点-->
        /*
        *  1. id属性: 标记切入点
        *  2.expression属性: "execution(* com.company.Book.*(..))" 定位到类的方法 ,"*" 表示全部
        */
        <aop:pointcut id="pointcut1" expression="execution(* com.company.Book.*(..))"></aop:pointcut>

        <!--设置切入面-->
        /*
        *  1. ref属性: 设置即将切入的配置对象的id
        */
        <aop:aspect ref="my book">
            <!--前置增强-->
            /*
             *  1.method属性: 设置你想切入MyBook类中的方法
             *  2.pointcut-ref属性:  切入点的id
             */
            <aop:before method="before1" pointcut-ref="pointcut1"></aop:before>

            <!--后置增强-->
            <aop:after-returning method="after1" pointcut-ref="pointcut1"></aop:after-returning>

            <!--环绕增强-->
            <aop:around method="round1" pointcut-ref="pointcut1"></aop:around>

        </aop:aspect>

    </aop:config>
</beans>

二. 创建Book类

public class Book {
    public void add(){
        System.out.println("add.....");
    }
}

三.创建Mybook类

public class Mybook {
    //前置增强
    public void before1(){
        System.out.println("前置增强.....");
    }
    //后置增强
    public void after1(){
        System.out.println("后置增强.....");
    }
    //环绕增强
    public void round1(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        //增强方法之前
        System.out.println("环绕增强之前.....");
        /*
         *  1. 调用这个方法才有效
         */
        proceedingJoinPoint.proceed();
        //增强方法之后
        System.out.println("环绕增强之后.....");
    }
}

四.创建测试类

/*
 *  1. 创建ApplicationContext对象,加载Bean1文件
 *  2.通过配置对象的id获取到Book对象
 */
ApplicationContext context = new ClassPathXmlApplicationContext("Bean1");
Book book = (Book) context.getBean("book");
book.add();  //调用Book类的add()方法

//打印结果
前置增强.....
环绕增强之前.....
add.....
环绕增强之后.....
后置增强.....

相关文章

网友评论

      本文标题:Java:spring框架(3)AOP面向切面

      本文链接:https://www.haomeiwen.com/subject/ebfrbttx.html