通过配置引介增强,引介增强和其他类型的增强是不一样的,他没有method,pointcaut和oint-ref属性.
首先需要在spring配置文件中加入如下类似的代码:
<!-- 引介增强的配置 -->
<aop:config proxy-target-class="true">
<aop:aspect>
<aop:declare-parents
types-matching="test.com.zayden.ipcs.aspects.Waiter+"
implement-interface="test.com.zayden.ipcs.aspects.IDeclareAdvice"
default-impl="test.com.zayden.ipcs.aspects.DeclareAdvice"
/>
</aop:aspect>
</aop:config>
2,添加动态实现的接口和他的默认实现类
package test.com.zayden.ipcs.aspects;
public interface IDeclareAdvice {
/**
* 被测试的方法
*/
public abstract void declareDeamo();
}
package test.com.zayden.ipcs.aspects;
import org.springframework.stereotype.Component;
/**
* 这个是引介增强的例子
* @author zayden
*
*/
@Component
public class DeclareAdvice implements IDeclareAdvice {
/* (non-Javadoc)
* @see test.com.zayden.ipcs.aspects.IDeclareAdvice#declareDeamo()
*/
@Override
public void declareDeamo(){
System.out.println("引介增强的测试方法...");
}
}
4.编写测试类
package test.com.zayden.ipcs.aspects;
import javax.annotation.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
@ContextConfiguration(locations = {"classpath:resources/applicationContext.xml"})
public class TestAspect extends AbstractTestNGSpringContextTests{
//@Autowired @Qualifier("nativeWaite")
@Resource
private Waiter nativeWaite;
@Test
public void testGreetTo(){
nativeWaite.greetTo("zayden");
((IDeclareAdvice)nativeWaite).declareDeamo();
}
}
运行测试,可以看到,上面的对象运行时动态实现了IDeclareAdvice 接口,并且继承了DeclareAdvice类