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  

转载于:https://www.cnblogs.com/xuejianbest/p/10284916.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值