CDI中自定义Bean是否必须在create()方法中调用push()?
push() in Their create() Method? Great question—this is one of those nuanced CDI details that trips up even experienced developers, so it’s totally worth breaking down clearly.
First, the straight answer from the CDI specification:
Contextual implementations (like your custom beans) are not required to call
push().
That’s your baseline—you won’t break compliance or basic functionality if you skip this call. But here’s where the practical value comes in: calling push() between instantiation and injection can help the container cut down on client proxy objects, which are normally required to handle circular dependencies.
What does this mean in real-world scenarios?
Let’s say you’re writing a Portable Extension and manually adding bean instances. When you create a bean instance, if you call push() on its context before performing injections, the container can resolve dependencies directly against the actual instance instead of spinning up a proxy. This is particularly useful for scopes tied to a specific context (like @RequestScoped or @SessionScoped):
- Without
push(), if there’s a circular dependency (Bean A depends on Bean B, which depends on Bean A), the container has to use a proxy to "stand in" for one bean until the other is fully initialized. - With
push(), the container already has the instance in the active context during injection, so it can wire dependencies directly, avoiding proxy overhead and making your bean handling cleaner.
It’s not a hard requirement, but it’s an optimization that pays off in complex dependency graphs, especially when working with custom extensions.
内容的提问来源于stack exchange,提问作者Laird Nelson

