Spring:AOP(切面)demo

项目目录结构

在这里插入图片描述

aop.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 id="log" class="aop.Log" />
    
    <bean id="test1" class="aop.Test">
        <constructor-arg value="test1" />
    </bean>
    <bean id="test2" class="aop.Test">
        <constructor-arg value="test2" />
    </bean>
    
    <aop:config>
        <aop:aspect ref="log">
            <aop:pointcut id="aopTest"
                expression="execution(* aop.Test.go(..))
                and bean(test1)"/>
            <aop:before pointcut-ref="aopTest" method="before" />
        </aop:aspect>
    </aop:config>
</beans>

execution(* aop.Test.go(..))中:*表示返回类型为任意,(..)表示方法参数为任意;
bean()接受bean的ID;
and表示都匹配则匹配。

Log.java

package aop;

public class Log {
    public void before(){
        System.out.println("before");
    }
}

Test.java

package aop;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    private String str;
    public Test(String str){
        this.str = str;
    }
    
    public void go(){
        System.out.println(str + " go");
    }
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"conf/aop.xml"});
        Test test1 = context.getBean("test1", Test.class);
        Test test2 = context.getBean("test2", Test.class);
        
        test1.go();
        test2.go();
    }
}

输出

before
test1 go
test2 go  
posted @ 2019-01-16 10:48  xuejianbest  阅读(350)  评论(0编辑  收藏  举报