随笔 - 2  文章 - 721  评论 - 6  阅读 - 35万

@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   溪水静幽  阅读(961)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示