@DeclareParents

  在使用基于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类型的对象使用

 

参考:

https://blog.csdn.net/elim168/article/details/78166296

 

posted on 2018-11-01 17:09  溪水静幽  阅读(945)  评论(1编辑  收藏  举报