Spring-AOP

Spring的AOP我的个人理解就是:

通过在Spring里面配置在原有基础的类的功能上加上一些其他的功能,并且原有功能是并不知道新加功能的存在的


注意事项:目标对象必须为接口,需要被实现


例子:

首先是创建增加功能的类 其内容是:

package com.gxa.bj.aspect;
import java.util.Date;
import org.aspectj.lang.ProceedingJoinPoint;
import commHelp.CommHelp;
public class SentInforMation {

//增强前的方法
      public void before()
      {
     System.out.println("the person has near to ATM");
      }
      
      //增强的方法
      public Object around(ProceedingJoinPoint joinpoint) throws Throwable
      {
      Object object  = joinpoint.proceed();
      String date = CommHelp.getDate(new Date());
      System.out.println("you had take money:200$.the time is:"+date+"");
      
  return object;
     
      }
      //增强后的方法
      public void after()
      {
     System.out.println("the bank hand deduction for your credit card");
      }
}


然后是目标对象及实现它的类:


目标对象:

package com.gxa.bj.service;
public interface TakeMoney 

{


public void takeMoney();

}

  实现目标对象的类:

package com.gxa.bj.service;
public class PersonMike implements TakeMoney {
@Override
public void takeMoney()

 {

System.out.println("Mike:I am try to catch some money");
}      
}


 Spring配置:

<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">


 <!-- 首先配置切面类 -->
<bean id="aspectbean" class="com.gxa.bj.aspect.SentInforMation"></bean>


   <!-- 配置目标对象类 -->

   <bean id="mike" class="com.gxa.bj.service.PersonMike"></bean>


   <aop:config>

   <aop:aspect id="takeMoneyAspect" ref="aspectbean">
      <aop:pointcut expression="execution(* com.gxa.bj.service.*.*(..))" id="pointcut"/>


      <!-- 要织入增强的方法的匹配 -->

      <aop:before method="before" pointcut-ref="pointcut"/>
       <aop:around method="around" pointcut-ref="pointcut"/>
       <aop:after method="after" pointcut-ref="pointcut"/>
   </aop:aspect> 
   </aop:config>
</beans>


测试:

package Test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.gxa.bj.service.*;


public class TestMike {


public static void main(String[] args){
  ApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
  TakeMoney ss =(TakeMoney) appcontext.getBean("mike");//必须要向上转型为父类才能获取bean
  
  ss.takeMoney();


}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值