This question already has answers here:
Backing beans (#ManagedBean) or CDI Beans (#Named)?
(5 answers)
Closed 6 years ago.
This might be a noob question, however in a lot of tutorials and examples I saw these annotations used as if they did the same thing.
However I ran into some limitations using the #Named one (especially with dependency injection etc.) I couldn't find a source where the difference is explained and I'd be very thankful if someone can give a rough overview on when to use one or the other.
#Named gives a CDI managed bean an EL name to be used in view technologies like JSF or JSP. Note that in a CDI application you don't need the #Named annotation to make a bean managed by CDI (thanks to #Karl for his comment).
#ManagedBean makes the bean managed by JSF and you can:
inject it into other #ManagedBean annotated beans (but not into #Named beans!)
access it from your views via expression language
See this related question for further information how injection works among both kind of beans.
Note that there is also a difference with the scope of the beans. They come from different packages but are named identically (JSF: javax.faces.bean, CDI: javax.enterprise.context , so it is often a source of error and confusion if you include the wrong class.
From my experience: You should use CDI beans whenever possible since they are more flexible than JSF managed beans. Only drawback is that CDI doesn't know a view scope, so you either need to fall back to #ManagedBean or use some third party extension like Seam.
EDIT: CDI supports ViewScope, more info on LINK
Related
This question already has answers here:
Backing beans (#ManagedBean) or CDI Beans (#Named)?
(5 answers)
Closed 6 years ago.
This might be a noob question, however in a lot of tutorials and examples I saw these annotations used as if they did the same thing.
However I ran into some limitations using the #Named one (especially with dependency injection etc.) I couldn't find a source where the difference is explained and I'd be very thankful if someone can give a rough overview on when to use one or the other.
#Named gives a CDI managed bean an EL name to be used in view technologies like JSF or JSP. Note that in a CDI application you don't need the #Named annotation to make a bean managed by CDI (thanks to #Karl for his comment).
#ManagedBean makes the bean managed by JSF and you can:
inject it into other #ManagedBean annotated beans (but not into #Named beans!)
access it from your views via expression language
See this related question for further information how injection works among both kind of beans.
Note that there is also a difference with the scope of the beans. They come from different packages but are named identically (JSF: javax.faces.bean, CDI: javax.enterprise.context , so it is often a source of error and confusion if you include the wrong class.
From my experience: You should use CDI beans whenever possible since they are more flexible than JSF managed beans. Only drawback is that CDI doesn't know a view scope, so you either need to fall back to #ManagedBean or use some third party extension like Seam.
EDIT: CDI supports ViewScope, more info on LINK
Currently I have only one controller AppController (SessionScope - ManagedBean) that handles all of the requests and logic of my system, but somehow this doesn't seem right. I want to make this project as modular as possible so it can be very easy to maintain.
I have read a little about Dependency Injection, but I just can't make it work, that is, I don't know what's the issue with the "scope" of the beans. For example, I have my AppController and my Users bean, but I can't make use of the AppController from the Users bean (although I have tried with dependency injection). I think that the logic of the users (edit names, set relationships, etc.) must be handled by the Users bean, but right now those tasks are handled by the AppController, which doesn't seem right.
The issue is, Is there any good tutorial where I can learn how to make a proper use of the JSF 2.0 framework? My objective is to make the AppController as light as possible. I have found several tutorials, but they seem to be more focused on older versions of the JSF or I just don't happen to understand them (maybe they are too technical, I don't know).
Any help with this would be very appreciated.
As to the concrete problem, you shouldn't have a single managed bean which acts as a front controller to handle all requests. JSF's own FacesServlet is supposed to do that. The common consensus is to have a single request/view scoped managed bean per <h:form> you have. And one or two session scoped bean(s) to represent the logged-in user and its settings like locale, if any. You could have an application scoped bean for applicationwide data such as dropdown constants.
As to the concrete question (which is rather subjective and per definition offtopic here, but ala), there is not really a simple tutorial for this. It's a matter of understanding what you're doing and what the code is doing and ultimately using the right tool for the job. In order to learn that, you've to read a self-respected JSF2 book from top to bottom and play a lot around with simple projects. JSF can't be learnt and fully understood in 1 day. It took me years. You can find useful links/references in our JSF wiki page.
I am trying to set up a web application stack based upon JBoss AS7 for small-scale research prototypes and student projects that meets following requirements:
I want to use AJAX-related scopes such as ViewScope -- or possibly a (View)AccessScope as in MyFaces Orchestra -- for my managed beans, in conjunction with PrimeFaces components.
JPA-based persistence should be fairly straightforward, without having to deal with the OpenSessionInView pattern etc.. The main problem I am having with JPA2 is the dreaded LazyInitializationException, especially in AJAX calls. I do not require manual control over conversations.
I want to use as few dependencies as possible, thus mostly relying on what is shipped with JBoss AS7.
Right now, I have set up a project with the following (mostly provided) Maven dependencies:
CDI
hibernate-2.0-api
jboss-ejb-api_3.1_spec
jboss-jsf-api_2.1_spec
jboss-annotations-api_1.1_spec
PrimeFaces 3
This looks pretty slim so far. What is missing is support for further JSF-specific scopes, and that I always get a LazyInitializationException when iterating over collections within a JSF page. Right now, my service classes for persistence look like this:
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
#Stateful #RequestScoped
public class TestEntityService implements Serializable {
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;
// ... some methods working with the entityManager ...
}
And my ResourceFactory bean:
public class ResourceFactory {
#Produces #PersistenceUnit
private EntityManagerFactory entityManagerFactory;
}
I unsuccessfully tried combinations with #Named instead of #Stateful, or #SessionScoped instead of #RequestScoped. However, I found that adding the Seam 3 Persistence, Solder & Faces modules seems to cure most of my problems, but this adds a ton of new dependencies to my project (e.g. seam-security, prettyfaces, drools, joda-time and further dependencies).
My questions are:
Would EJBs be of any help w.r.t. the LazyInitializationException? Or am I actually already using EJBs here due to the #Stateful annotation? I took this from a jboss-as sample application, but I am utterly confused by the differences between all these #ManagedBean, #Named, #Stateful, #LocalBean annotations... all I know is that I somehow need to bind the lifespan of my entity managers to the scope of the service bean.
Does anybody know other easy ways of getting around this problem? Using EAGER fetching is not an option as this only seems to work if there is not more than one collection per entity...
I just read about Apache CODI, which seems to be the CDI successor of MyFaces Orchestra. Is this a better alternative to Seam Faces? As far as I can see, it offers a ViewScope and ViewAccessScope, but nothing with regard to transaction management.
It would be great if someone with more experience in this field could shed some light on this -- I am currently a bit confused because there are so many libraries out there dealing with similar issues, albeit most apparently not compatible with each other (see e.g. here). Thanks!
You're right. All of this is quite confusing. This confusion comes from JSF2 and CDI providing the same feature. As these two specifications needs to work without the other they have similare annotations for Scope and EL exposition. This blog post details these confusing areas and how to make the right choice. To make it short, when using CDI with JSF, always use CDI annotations, or annotations that CDI will control thru an extension (as javax.faces.ViewScoped when you have Seam Faces or CODI in your project)
To answer to your questions
You're already using EJB with #Stateful annotation. EJB won't help you directly with LazyInitializationException but they are more natural option to deal with transaction and database (you can't use #PersistenceContext annotation in a pojo CDI bean). Regarding the confusing annotations I already answered
I have good experience with Seam Persistence. This CDI extension creates a managed Entity Manager that lives in conversation and allow the use of transaction outside EJB (if you don't have a Java EE container). Using this Entity Manager reduces significantly Lazy Lodaing issues. It can be inject in a stateless EJB which manage your DAO thanks to CDI magic that allows injecting Bean of different scope. Used in conjonction of Seam Faces you'll get the support of JSF ViewScope for CDI and a transaction tied to JSF lifecycle
I don't have any experience with CODI which seems to bring useful functionalities like nested conversation.
In conclusion, be aware that Seam and CODI are in a merge process right now in Apache Delta Spike, so the solution you're about to build should be re-evaluated in the coming month to include Delta Spike in the equation.
Honestly, there is no "one-size-fits-all" for CDI. Seam3 works great, MyFaces CODI works great, it really depends on what you want. For your situation, honestly, it seems like the easiest thing to do would be to create your own ViewScoped extension for your project, or pull the necessary parts from Seam 3 or CODI.
I'm starting off with Java EE 6 after not touching EE for years (I've been in Spring land for a while).
In JSF 2, am I right in thinking that we don't really have controllers any more. That job is done by managed beans?
If so, is it considered normal practice to then inject a 'Service' class (with CDI) into my managed bean to handle the business logic (and subsequently call DAOs)?
I bought a book (PacktPub's 'EE 6 with Netbeans') and read quite a few tutorials but I'm still a little unclear on how to do it right.
As a bonus question, is there a reference 'PetStore' style app that I can download that shows it all linked together in a best-practices kind of way?
Thanks
In JSF 2, am I right in thinking that we don't really have controllers
any more. That job is done by managed beans?
It depends on how you define the term controller. Some people confuse managed beans with controllers but they rather belong to the model part of MVC or are located "between" model, view and controller (see this great answer by Arjan Tijms to a similar question).
If so, is it considered normal practice to then inject a 'Service'
class (with CDI) into my managed bean to handle the business logic
(and subsequently call DAOs)?
This can be done and is normal practice (I do it in all of my projects). But note, that injection does not always work as expected, so for instance you cannot inject a managed bean into a CDI bean (see my answer to a similar question).
As a bonus question, is there a reference 'PetStore' style app that I
can download that shows it all linked together in a best-practices
kind of way?
You could take a look at the Netbeans tutorials. There you find a lot of information about the topic. A visit to BalusC's blog is also highly recommended.
We're using Spring Security to control access to some services. It is working fine for 95% of the classes. However, there are two classes where the security annotations are being ignored completely. The security interceptor is not in the list of interceptors for those two classes when the services are called at runtime.
As far as I can tell, there are no differences between these classes and others that work. The basic structure is the same, other annotations used are the same. Scanning the classpath for the annotations picks up the classes. Other classes in the same package work fine.
I'm not very experienced with Spring Security, so I was hoping that someone could point me in the direction of something that I may have overlooked.
If anyone else is interested, what was happening is that we had a circular injection reference between two classes. Class A had a reference to Class B which had a reference to Class A.
When Spring attempted to create the bean for class A, it encountered the circular reference and created an early bean reference for class A which was then proxied. However, the step to add the method pointcuts occurs after all this, so the class got proxied without the security interceptor.