Introductions允许一个切面声明一个实现指定接口的通知对象,并且提供了一个接口实现类来代表这些对象。
先看下面的例子:
配置文件
<?xml version="1.0" encoding="UTF-8"?>Plane.java
<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-3.2.xsd">
<bean id="plane" class="com.wry.bean.Plane"></bean>
<bean id="myAspect" class="com.wry.aspect.MyAspect"></bean>
<aop:config>
<aop:aspect id="myAspectAOP" ref="myAspect">
<aop:declare-parents types-matching="com.wry.bean.Plane(*)"
implement-interface="com.wry.bean.Vehicle"
default-impl="com.wry.bean.VehicleImpl"/>
</aop:aspect>
</aop:config>
</beans>
package com.wry.bean;Vehicle.java
public class Plane {
public void fly(){
System.out.println("plane flying");
}
}
package com.wry.bean;VehicleImpl.java
public interface Vehicle {
public void drive();
}
package com.wry.bean;Demo.java
public class VehicleImpl implements Vehicle{
@Override
public void drive() {
System.out.println("vehicle driving");
}
}
package com.wry.test;程序输出
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.wry.bean.Vehicle;
public class Demo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
Vehicle vehicle = (Vehicle)context.getBean("plane");
vehicle.drive();
}
}
vehicle driving
由<aop:aspect>中的<aop:declare-parents>元素声明该元素用于声明所匹配的类型拥有一个新的parent。
这句话这样理解,在<aop:declare-parents>标签中,types-matching是Plane类,implement-interface是Vehicle接口。在Demo类中Vehicle vehicle = (Vehicle)context.getBean("plane"); 将plane对象转化为vehicle对象而且不会报错,意思是给Plane类增加了一个父类Vehicle。上面“提供了一个接口实现类来代表这些对象”,即用Vehicle接口代表plane对象,给它增加一个父类才能转化。