Spring--AOP--基本配置(Intruductions-- Advice 动态代理)

来源:互联网 发布:广东省云计算应用协会 编辑:程序博客网 时间:2024/06/05 23:54

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();    }}
原创粉丝点击