Spring_使用注解引入新功能

人行犹可复,岁月难可追。

  Java并不是动态语言,类编译完成后,很难在为该类添加新的功能,但是利用被称为引入的AOP概念,我们可以利用切面为Spring Bean添加新的方法。

  使用@DeclareParents注解,将接口引入到Spring Bean中。

  @DeclareParents注解由三部分组成:

    1)value属性指定了哪种类型的bean要引入该接口。加号(+)表示是该类型的所有子类型,而不是该类型本身。

    2)defaultImpl属性指定了为引入功能提供实现的类。

    3)@DeclareParents注解所标注的静态属性指明了要引入的接口。

package chapter4.practice2;

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

@Aspect
public class EnableFlyIntroducer {
    @DeclareParents(value="chapter4.practice2.People+",defaultImpl=ChinesePeople.class)
    public static EnableFly enableFly;
}
package chapter4.practice2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class PeopleConfg {
    
    @Bean
    public People people() {
        return new ChinesePeople();
    }
}

  Spring的自动代理机制将会获取到ChinesePeople bean的声明,当Spring发现一个bean使用了@Aspect注解时,Spring就会创建一个代理,然后将调用委托给被代理的bean或被引入的实现,这取决于调用的方法属于被代理的bean还是属于被引入的接口。

猜你喜欢

转载自www.cnblogs.com/dandelZH/p/8947664.html
今日推荐