zoukankan      html  css  js  c++  java
  • Spring Aop(六)——@DeclareParents介绍

    转发:https://www.iteye.com/blog/elim-2395410

    6 @DeclareParents介绍

    @DeclareParents注解也是Aspectj提供的,在使用基于Aspectj注解的Spring Aop时,我们可以在切面中通过@DeclareParents指定满足指定表达式的类将自动实现某些接口。这个只是在运行时会将生成的代理类实现指定的接口。有接口就会有实现,对应的实现类也需要我们在@DeclareParents声明自动实现的接口时声明。现假设我们有一个接口叫CommonParent,其实现类叫CommonParentImpl,代码如下。

    public interface CommonParent {
    
    	public void doSomething();
    	
    }
    public class CommonParentImpl implements CommonParent {
    
    	public void doSomething() {
    		System.out.println("-----------do something------------");
    	}
    
    }

    然后我们希望我们的所有的Service实现类都可以在运行时自动实现CommonParent接口,即所有的Service实现类在运行时都可以被当做CommonParent来使用。那我们可以定义如下这样一个切面类和对应的Advice。

    @Component
    @Aspect
    public class DeclareParentsAspect {
    
    	@DeclareParents(value="com.elim.spring.aop.service..*", defaultImpl=CommonParentImpl.class)
    	private CommonParent commonParent;
    	
    	@Before("bean(userService) && this(commonParent)")
    	public void beforeUserService(CommonParent commonParent) {
    		commonParent.doSomething();
    	}
    	
    }

    如上,我们先在切面类中声明了一个CommonParent类型的属性,然后在上面使用了@DeclareParents注解表示我们需要把CommonParent声明为某些指定类型的父接口,然后通过@DeclareParents的value属性指定需要作用的类的形式,其语法和Pointcut表达式类似。通过defaultImpl属性指定默认CommonParent接口的实现类是CommonParentImpl。然后我们声明了一个before类型的Advice,在其中直接把我们的bean当做CommonParent类型的对象使用。

    整个过程就是这样的,非常简单。但是笔者暂时还没有发现这个在实际应用中可以应用于哪些场景,欢迎交流。

    参考文档 1、官方文档

    (注:本文是基于Spring4.1.0所写,写于2017年1月22日星期日)

  • 相关阅读:
    Shiro 集成Spring 使用 redis时 使用redisTemplate替代jedisPool(五)
    shiro 实现 网站登录记住我功能 学习记录(四)
    magento2根据属性id或code来添加options
    微信小程序-注册程序app.js
    微信小程序-目录结构
    如何在最新的PHP 7.1.0上安装和运行最新的Magento 2.1.3
    添加新的php版本到wamp中
    全局使用php
    PHP设计模式之单例模式
    SourceTree使用
  • 原文地址:https://www.cnblogs.com/Jeely/p/11947579.html
Copyright © 2011-2022 走看看