Grizzly
Grizzly

Reputation: 65

JEE: How to intercept a @PostCostruct method?

I have a bean having:

One of those interceptors has methods annotated with

In each of those methods I put some logging, so I can see which and when the interceptor methods are called. And the call order looks like this:

I was very surprised realizing that the @PostConstruct is not called during the bean's @PostConstruct method call, but between the construction of the bean and calling the bean's @PostConstruct method. Also the call of the bean's @PostConstruct method is not intercepted at all, not by the interceptor's @PostConstruct method nor bi its @AroundInvoke method.

Is there any mistake on my side / my programs side?

Is there any way to intercept the bean's @PostConstruct method (same goes for the @PreDestroy method)?

I need to prepare the context(s) and fill them with some content. In addition it would be also nice for other method deep down the call stack later to know that the call was triggered by the container through one of those two methods.

Upvotes: 1

Views: 667

Answers (1)

Grizzly
Grizzly

Reputation: 65

As I couldn't find any answer on that in the Internet, I went through some debugging and found out the following (used WildFly 15.0.1.Final):

When a bean is instantiated:

  • Entering interceptor's @AroundConstruct (InvocationContext: Constructor set)
  • Executing bean's constructor
  • Leaving interceptor's @AroundConstruct (InvocationContext: Constructur and target set)
  • Entering interceptor's @PostConstruct (InvocationContext: Constructur and target set)
  • Executing bean's @PostConstruct
  • Leaving interceptor's @PostConstruct (InvocationContext: Constructur and target set)

This means that you don't know which method is called, you only know that the @PostConstruct method of the bean is called. I guess that's because the @PostConstruct method of the bean is executed as some kind of interceptor, but that is only an assumption on my side.

When you execute a bean's method:

  • Entering interceptor's @AroundInvoke (InvocationContext: Method and target set)
  • Executing bean's method
  • Leaving interceptor's @AroundInvoke (InvocationContext: Method and target set)

When a bean is destroyed:

  • Entering interceptor's @PreDestroy (InvocationContext: Target set)
  • Executing bean's @PreDestroy
  • Leaving interceptor's @PreDestroy (InvocationContext: Target set)

I hope that this will be also helpful to others.

Upvotes: 1

Related Questions