Spring中AOP的Introductions使用介绍

    Spring中AOP的Introductions翻译成中文为简介。
    Introductions允许一个切面声明一个实现指定接口的通知对象,并且提供了一个接口实现类来代表这些对象。
    先看下面的例子:

配置文件

<?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"   
       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>
Plane.java

package com.wry.bean;

public class Plane {

	public void fly(){
		System.out.println("plane flying");
	}
}
Vehicle.java

package com.wry.bean;

public interface Vehicle {
	public void drive();
}
VehicleImpl.java

package com.wry.bean;

public class VehicleImpl implements Vehicle{

	@Override
	public void drive() {
		System.out.println("vehicle driving");
	}

}
Demo.java
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对象,给它增加一个父类才能转化。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值