Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject vs ManagedProperty [duplicate]

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.

like image 743
maralbjo Avatar asked Aug 31 '12 13:08

maralbjo


2 Answers

@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.

like image 127
Alonso Dominguez Avatar answered Sep 20 '22 06:09

Alonso Dominguez


I would favour CDI over managed beans whenever possible. CDI is richer in deploy-time dependency checking and its proxy support prevents scope leak. This makes it easier to verify the correctness of your model. Producers can generally be used to provide glue code where necessary.

  • CDI spec
  • Blog post on CDI and EL
like image 42
McDowell Avatar answered Sep 22 '22 06:09

McDowell