Inject vs ManagedProperty [duplicate]
Asked Answered
W

2

13

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.

Wiltz answered 31/8, 2012 at 13:6 Comment(0)
P
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.

Periwinkle answered 31/8, 2012 at 13:20 Comment(0)
W
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.

Whang answered 31/8, 2012 at 13:58 Comment(1)
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.Ermin

© 2022 - 2024 — McMap. All rights reserved.