Spring-AOP简单使用方法

顾名思义 AOP(Aspect oriented Programming)字面意思是面向切面编程,aop所带来的好处是能提取具有共同功能的代码块,比如用户取款流程需要用到1.用户密码的验证;2.用户查询余额需要用到密码的验证 那么两者之间的共同密码验证功能的逻辑实现则可以提取出来,提取出来的部分称为切面。以下为aop的小小案例(有两个HelloWord类,它们都需要打印时间毫秒,那么我们可以抽取打印时间作为切面)


1.操作AOP需要用到的jar包为


2.创建HellWord的接口,声明两个方法sayHello()dopoint()

package com.aop;

public interface HelloWord {
	public void sayHello();
	public void dopoint();

}

3.分别实现HellWord接口

package com.aop.hw;

import com.aop.HelloWord;

public class HelloWordImp2 implements HelloWord {

	@Override
	public void sayHello() {
		System.out.println("我是HelloWord2");
		
	}

	@Override
	public void dopoint() {
		System.out.println("我是dopoint2");
	}
  
}

package com.aop.hw;

import com.aop.HelloWord;
public class HelloWordImp1 implements HelloWord {

	@Override
	public void sayHello() {
		System.out.println("我是HelloWord1");
	}

	@Override
	public void dopoint() {
		System.out.println("我是dopoint1");
	}

}

4.创建一个时间切面TimerAspect类

package com.aop;

public class TimerAspect {
   public void timer() {
	   System.out.println(System.currentTimeMillis());
   }
}

5.配置applicationContext.xml文件,注意在配置xml文件的时候,这里expression="execution(* com.aop.hw.*.*(..))"需要注意,两个.*.*代表的是包下的类下的所有方法,<aop:config  proxy-target-class="true">这条语句中的proxy-target-calss=“true”需要加入,否则报错

<?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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
            
            
            <bean id="hello1" class="com.aop.hw.HelloWordImp1"></bean>
            <bean id="hello2" class="com.aop.hw.HelloWordImp2"></bean>
            <bean id="timerAspect" class="com.aop.TimerAspect"></bean>
           
           <aop:config  proxy-target-class="true">
              <aop:aspect id="timer" ref="timerAspect">
                 <aop:pointcut id="addAllMethod"  expression="execution(* com.aop.hw.*.*(..))" />
                 <aop:before method="timer" pointcut-ref="addAllMethod" />
                 <aop:after method="timer" pointcut-ref="addAllMethod" />
                 
              </aop:aspect>
           </aop:config>
</beans>





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值