12

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.

maralbjo
  • 953
  • 1
  • 10
  • 16

2 Answers2

9

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

Alonso Dominguez
  • 7,374
  • 1
  • 24
  • 37
6

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.

McDowell
  • 102,869
  • 29
  • 193
  • 261
  • 2
    I would add this, similar to what's below, you have things like EJBs you can inject with CDI. You can also keep them out of your view if you don't give them a @Name (which simply makes them available to EL). Using CDI also gives you extension points greater than what is available in JSF, but that's not part of the question :) I suggest sticking with CDI. – LightGuard Aug 31 '12 at 20:37