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();
}
}