Spring AOP-为切面引入功能

一、情景

      一般情况下,如果现有功能完成编译后,在不改变源码或无法获取源码的情况下,很难再为其添加新的功能,此时Spring AOP可以为切面添加新的功能。

二、实现

package com.giser.encore;

/**
 * 增强的功能接口 
 */
public interface Encoreable {
	void performEncore();
}
package com.giser.encore.impl;

import com.giser.encore.Encoreable;

/**
 * 增强的功能实现类
 */
public class DefaultEncoreable implements Encoreable {

	@Override
	public void performEncore() {
		System.out.println("DefaultEncoreable");
	}

}

创建切面增强类

package com.giser.encore;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

@Aspect
public class EncorealbeIntroducer {
	
	@DeclareParents(value = "com.giser.aop.Performance+",  // 指定那种接口类型的bean需要引入该接口,+号标识是Performance的所有子类,而非其本身
			defaultImpl = com.giser.encore.impl.DefaultEncoreable.class) // 指定了为引入该功能提供实现的类
	public static Encoreable encoreable; // 指明了要引入的接口
}

测试:

package com.giser.aoptest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.giser.aop.Performance;
import com.giser.encore.Encoreable;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {"classpath:spring.xml"})
public class SpringTest3 {
	
	@Autowired
	private Performance performance;
	
	@Test
	public void testPerformance() {
		performance.perform();
		Encoreable encoreable = (Encoreable) performance;
		encoreable.performEncore();
	}
	
}

结果:

Silencing cell phones
takeSeats
Silencing cell phones
takeSeats
gis performance
applause
applause
DefaultEncoreable

可以看到已经有了增强功能。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值