上篇博客写到了Spring AOP,不管是前置增强,后置增强,引入增强都是对方法的增强,但是是否考虑过对类进行增强呢?!伟大的spring做到了,只是换了一种说法:Introduction(引入)
首先我们来说一下引入增强的目的:动态的让被增强的类实现一个接口;下面就写一下代码吧:
定义了一个新接口 Apology:
/**
* 道歉接口
* @author 陈丽娜
* @version 2015年5月27日下午8:15:47
*/
public interface Apoloy {
/**
* say sorry
* @author 陈丽娜
* @version 2015年5月27日下午8:16:30
* @param name 名称
*/
public void saySorry(String name);
}
定义一个增强类,需要继承:org.springframework.aop.support.DelegatingIntroductionInterceptor类并同时实现Apoloygy接口,需要实现Apploy的方法。
/**
* 引入增强
* @author 陈丽娜
* @version 2015年5月30日下午7:56:35
*/
@Component
public class GreetingIntroAdvice extends DelegatingIntroductionInterceptor
implements Apoloy {
/**
* 实现saySorry方法
*/
@Override
public void saySorry(String name) {
System.out.println(name + "I am sorry !");
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// TODO Auto-generated method stub
return super.invoke(mi);
}
}
我们需要拿以上的类去丰富GreetingImpl类,那我们需要做什么呢?看看配置文件吧:
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/beans/aop
http://www.springframework.org/schema/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 在指定的包中(com.tgb.*)扫描@componet注解的类 -->
<context:component-scan base-package="com.tgb"></context:component-scan>
<bean id = "greetingImpl" class = "com.tgb.aop.service.impl.GreetingImpl">
<property name="test">
<value>你好你好你好呀</value>
</property>
</bean>
<!-- 定义一个代理类 -->
<bean id = "springProxy" class ="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="com.tgb.aop.service.Apoloy"/> <!-- 需要动态实现的接口 -->
<property name="target" ref= "greetingImpl"/> <!-- 目标类,打招呼的实现类 -->
<property name="interceptorNames" value="greetingIntroAdvice"></property> <!-- 引入增强类 -->
<property name="proxyTargetClass" value= "true"></property>
</bean>
</beans>
测试代码:
/**
* 引用增强测试
* @author 陈丽娜
* @version 2015年5月27日下午8:49:38
*/
@Test
public void SpringIntroductionTest(){
//读取xml文件 AOP\src\META-INF
ApplicationContext context = new ClassPathXmlApplicationContext("spring-introduction.xml");
GreetingImpl greeting = (GreetingImpl) context.getBean("springProxy");
greeting.sayHello("greetingImpl单纯的sayhello");
Apoloy apoloyProxy = (Apoloy)greeting; // 把打招呼类 强制向上强转
apoloyProxy.saySorry("引入增强效果");
}
运行效果:
其实个人感觉引入增强还是很神奇的,测试中说到一句:向上强转,这里就说一下转型吧:
转型是在继承的基础上而言的,继承是面向对象语言中,代码复用的一种机制,通过继承,子类可以复用父类的功能,如果父类不能满足当前子类的需求,则子类可以重写父类中的方法来加以扩展。
那么向上转型:子类引用的对象转换为父类型称为向上转型,也就是说将子类对象转为父类对象(父类对象可以是接口)
这里的引用增强就是把GreetingImpl向上转型成了Apoloy接口。是不是很神奇呀?!