一、情景
一般情况下,如果现有功能完成编译后,在不改变源码或无法获取源码的情况下,很难再为其添加新的功能,此时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
可以看到已经有了增强功能。