Intruductions简介: 在Spring AOP中,将introduction当作advice来处理。与一般的advice一样,introduction advice相当于一种特殊类型的拦截器。
作用: 可以动态的为某类添加父类,以添加该类的新功能
特点: introduction是一个更加特殊的、但功能更加强大的切入类型—-利用它可以实现为给定的类动态地添加新功能(动态的为指定类添加父类)。
应用场景: 比如要为100个对象添加添加记录更新时间的功能,如果对每个类进行修改不但破换了对象的完整性,还特别麻烦。这个时候使用Introduction Advice为100个对象动态添加现有类添加记录更新时间的功能(也可添加字段属性),使用该功能的时候才会动态的调用此方法。
缺点: 这样灵活的添加功能,是以牺牲性能为代价的,使用之前要慎重考虑。
<————————————————–>
相关配置
<?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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<bean id="moocAspect" class ="com .imooc .aop .schema .advice .MoocAspect ">< /bean >
<bean id="aspectBiz" class =" com .imooc .aop .schema .advice .biz .AspectBiz ">< /bean >
<aop: config>
<!-- 配置切面aspect -->
<aop: aspect id="moocAspectAop" ref="moocAspect" >
<!-- 配置切入点 pointcut **********************切入点执行以Biz 结尾的所有类的方法(注意第一个*后边的空格不能少
) -->
<aop: pointcut
expression="execution(* com.imooc.aop.schema.advice.biz.*Biz.*(..))"
id="moocPointCut" />
<!--配置Intruductions -- Advice ***************************匹配该包下所有的类 -->
<aop: declare-parents types-matching="com.imooc.aop.schema.advice.biz.*(+)"
<!-- 配置接口 -->
implement-interface="com.imooc.aop.schema.advice.biz.Fit"
<!-- 配置实现类 -->
default-impl="com.imooc.aop.schema.advice.biz.FitImpl" />
</aop:aspect>
</aop :config>
</beans>
相关实现代码
接口:
package com.imooc.aop.schema.advice.biz;
public interface Fit {
void filter();
}
实现类:
package com.imooc.aop.schema.advice.biz;
public class FitImpl implements Fit {
@Override
public void filter() {
System .out.println("FitImpl filter " );
}
}
为Bean容器中的某个对象动态添加filter()方法:
该对象没有任何方法但能执行动态添加的方法
package com.imooc.aop.schema.advice.biz;
public class AspectBiz {
public static void main(String [] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("spring-aop-schema-advice.xml" );
Fit f = (Fit ) applicationContext.getBean("aspectBiz" );
f.filter();
}
}