【问题标题】:JEE: How to intercept a @PostCostruct method?JEE:如何拦截@PostCostruct 方法?
【发布时间】:2020-01-21 16:25:35
【问题描述】:

我有一个豆子有:

  • void initialize() 方法用 @PostConstruct 注释。
  • 使用 @PreDestroy 注释的 void release() 方法。
  • 其他一些方法。
  • 此外,该 bean 有一个 @Interceptors 注释定义了一些拦截器。

其中一个拦截器的方法带有注释

  • @AroundConstruct
  • @AroundInvoke
  • @AroundTimeout
  • @PostConstruct
  • @PreDestroy

在这些方法中的每一个中,我都添加了一些日志记录,因此我可以查看调用了哪些拦截器方法以及何时调用了这些方法。调用顺序如下所示:

  • 进入拦截器的@AroundConstruct 方法。 InvocationContext:目标是null,方法是null,构造函数已设置。
  • Beans 构造函数被调用。
  • 调用存在于Interceptor 的@AroundConstruct 方法中。 InvocationContext:目标为bean实例,方法为null,构造函数已设置。
  • 拦截器的@PostConstruct 方法被调用,调用proceed() 并返回。 InvocationContext:目标为bean实例,方法为null,构造函数已设置。
  • 在上一次调用完全返回后,将调用 bean 的 @PostConstruct 方法。

我很惊讶地发现@PostConstruct 不是在bean 的@PostConstruct 方法调用期间调用,而是在bean 的构造和调用bean 的@PostConstruct 方法之间。此外,bean的@PostConstruct方法的调用根本不会被拦截,拦截器的@PostConstruct方法和@AroundInvoke方法都不会。

我/我的程序方面有什么错误吗?

有什么办法可以拦截bean的@PostConstruct方法(@PreDestroy方法也一样)?

我需要准备上下文并用一些内容填充它们。此外,稍后调用堆栈深处的其他方法也可以知道调用是由容器通过这两种方法之一触发的。

【问题讨论】:

    标签: interceptor postconstruct java-ee-8 wildfly-15 predestroy


    【解决方案1】:

    由于我在互联网上找不到任何答案,因此我进行了一些调试并发现了以下内容(使用 WildFly 15.0.1.Final):

    当一个 bean 被实例化时:

    • 进入拦截器的@AroundConstruct(InvocationContext:构造函数集)
    • 执行 bean 的构造函数
    • 离开拦截器的@AroundConstruct(InvocationContext:构造函数和目标集)
    • 进入拦截器的@PostConstruct(InvocationContext: Constructur and target set)
    • 正在执行 bean 的 @PostConstruct
    • 离开拦截器的@PostConstruct(InvocationContext:构造函数和目标集)

    这表示你不知道调用了哪个方法,只知道调用了bean的@PostConstruct方法。我猜那是因为 bean 的 @PostConstruct 方法是作为某种拦截器执行的,但这只是我的一个假设。

    当你执行一个bean的方法时:

    • 进入拦截器的@AroundInvoke(InvocationContext:方法和目标集)
    • 执行bean的方法
    • 离开拦截器的@AroundInvoke(InvocationContext:方法和目标集)

    当一个 bean 被销毁时:

    • 进入拦截器的@PreDestroy(InvocationContext:目标集)
    • 执行bean的@PreDestroy
    • 离开拦截器的@PreDestroy(InvocationContext:目标集)

    我希望这对其他人也有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 2011-04-16
      • 1970-01-01
      • 2017-06-02
      • 2011-06-11
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多