Inject vs ManagedProperty

maralbjo picture maralbjo · Aug 31, 2012 · Viewed 8.5k times · Source

Okay, so I have a JSF backing bean that needs a reference to another (@NoneScoped) bean.

Should I @Inject it or use @ManagedProperty to obtain an instance reference from the container?

Why use one and not the other, in my mind the two approaches achieve the same thing.

Answer

Alonso Dominguez picture Alonso Dominguez · Aug 31, 2012

@ManagedProperty and @NoneScoped comes from the JSF 2.0 spec whilst @Inject comes from the CDI spec.

If you are just working on a servlet application that doesn't make any use of any of the others JavaEE 6 features, then go for @ManagedProperty. That annotation has also an advantage against @Inject: you can use EL (expression language) with it (although there are workarounds to get that in CDI).

Both annotations/containers seem to achieve "the same thing" but in very different ways and they work with different containers. Beans managed by CDI will be available to JSF but not viceversa. If you are annotating your beans with JSF specific annotations then forget about using custom qualifiers, interceptors, producer methods, etc. I usually prefer the approach with CDI because, at the end, it is more sophisticated but the choice will depend on your actual needs.

Wrapping it up, as it seems that you are just using JSF features then stick to the @ManagedProperty (CDI can't understand @NoneScoped annotations, in CDI all beans are under the @Default scope if none specified). Switching to CDI in your project might mean to replace not just the @ManagedProperty for an @Inject one, but all your @RequestScoped (and so on) for the CDI-specific ones.