Preferred method to get another bean: evaluating EL or #Inject - jsf

We can get jsf bean by two ways:
JobApplicant jobApplicant = (JobApplicant) FacesUtils.getManagedBean("jobApplicant");
or
Ingecting the property
#Inject
JobApplicant jobApplicant //getter and setter required
In first way we can get a bean right in method, so in does not allocate memory. If it be class member (with Inject) it allways requred some memory to hold a reference to that bean. Also in this case the scope of jobApplicant must be at least not shorter than a scope of outer bean which inject the jobApplicant. But in case of using utils the scope could be a view for example which is shorter than session scope of outer bean, yea?
What is the best method to get a bean?

One of the key benefits of dependency injection is the inversion of control pattern. Instead of creating instances yourself, you tell the manageing container which dependencies you need.
So you should stick to the "#Inject" approach whenever possible. You can use it with fields, constructors and setters, so your statement that it requires getters/setters is not true.
You will notice that testing gets a lot easier when your code does not call any static factory methods but just requires injecting a bean.

Related

Primefaces: <p:dataTable>'s data source change or concurrency operation will cause the inconsistent parameter passing from jsf-el to backing bean [duplicate]

I've a data table as below:
<h:dataTable value="#{bean.items}" var="item">
I'd like to populate it with a collection from the database obtained from a service method so that it is immediately presented when the page is opened during an initial (GET) request. When should I call the service method? And why?
Call it before page is loaded. But how?
Call it during page load. How?
Call it in the getter method. But it is called multiple times.
Something else?
Do it in bean's #PostConstruct method.
#ManagedBean
#RequestScoped
public class Bean {
private List<Item> items;
#EJB
private ItemService itemService;
#PostConstruct
public void init() {
items = itemService.list();
}
public List<Item> getItems() {
return items;
}
}
And let the value reference the property (not method!).
<h:dataTable value="#{bean.items}" var="item">
In the #PostConstruct you have the advantage that it's executed after construction and dependency injection. So in case that you're using an EJB to do the DB interaction task, a #PostConstruct would definitely be the right place as injected dependencies would not be available inside a normal constructor yet. Moreover, when using a bean management framework which uses proxies, such as CDI #Named, the constructor may or may not be called the way you expect. It may be called multiple times during inspecting the class, generating the proxy, and/or creating the proxy.
At least do not perform the DB interaction job in the getter, unless it's lazy loading and you really can't do anything else. Namely, it would be invoked during every iteration round. Calling the service method during every iteration round is plain inefficient and may end up in "weird" side effects during presentation and postbacks, such as old values from DB seemingly still sticking around in the model instead of new submitted values.
If you rely on GET request parameters, then use <f:viewParam> and <f:viewAction> instead. See also Creating master-detail pages for entities, how to link them and which bean scope to choose.
If you want to preserve the model (the items property) across postbacks on the same view (e.g. CRUD table/dialog), then make the bean #ViewScoped, else the model won't be in sync with the view when the same model is concurrently edited elsewhere. See also Creating master-detail table and dialog, how to reuse same dialog for create and edit.
If you utilize JPA's #Version feature on the model, then you can catch OptimisticLockException to deal with it and show a message like "The data has been edited by someone else, please refresh/review if the desired changes are as intended". See also Letting the presentation layer (JSF) handle business exceptions from service layer (EJB).
See also:
Why JSF calls getters multiple times
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
How to choose the right bean scope?
JSF Controller, Service and DAO

preRenderView not working during a method call [duplicate]

I've a data table as below:
<h:dataTable value="#{bean.items}" var="item">
I'd like to populate it with a collection from the database obtained from a service method so that it is immediately presented when the page is opened during an initial (GET) request. When should I call the service method? And why?
Call it before page is loaded. But how?
Call it during page load. How?
Call it in the getter method. But it is called multiple times.
Something else?
Do it in bean's #PostConstruct method.
#ManagedBean
#RequestScoped
public class Bean {
private List<Item> items;
#EJB
private ItemService itemService;
#PostConstruct
public void init() {
items = itemService.list();
}
public List<Item> getItems() {
return items;
}
}
And let the value reference the property (not method!).
<h:dataTable value="#{bean.items}" var="item">
In the #PostConstruct you have the advantage that it's executed after construction and dependency injection. So in case that you're using an EJB to do the DB interaction task, a #PostConstruct would definitely be the right place as injected dependencies would not be available inside a normal constructor yet. Moreover, when using a bean management framework which uses proxies, such as CDI #Named, the constructor may or may not be called the way you expect. It may be called multiple times during inspecting the class, generating the proxy, and/or creating the proxy.
At least do not perform the DB interaction job in the getter, unless it's lazy loading and you really can't do anything else. Namely, it would be invoked during every iteration round. Calling the service method during every iteration round is plain inefficient and may end up in "weird" side effects during presentation and postbacks, such as old values from DB seemingly still sticking around in the model instead of new submitted values.
If you rely on GET request parameters, then use <f:viewParam> and <f:viewAction> instead. See also Creating master-detail pages for entities, how to link them and which bean scope to choose.
If you want to preserve the model (the items property) across postbacks on the same view (e.g. CRUD table/dialog), then make the bean #ViewScoped, else the model won't be in sync with the view when the same model is concurrently edited elsewhere. See also Creating master-detail table and dialog, how to reuse same dialog for create and edit.
If you utilize JPA's #Version feature on the model, then you can catch OptimisticLockException to deal with it and show a message like "The data has been edited by someone else, please refresh/review if the desired changes are as intended". See also Letting the presentation layer (JSF) handle business exceptions from service layer (EJB).
See also:
Why JSF calls getters multiple times
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
How to choose the right bean scope?
JSF Controller, Service and DAO

Are JSF managed beans Singleton in nature? [duplicate]

could some explain what a none scope is and purpose of it?
Suppose if i have a bean in
request scope as r1
session scope as s1
application scope a1
and say i inject none scope bean n1 in to each of above scopes then i find that n1 gets
instantiated for each parent bean when ever its parent bean[r1/s1/a1] is instantiated.
none scope bean in a1 is available throughout in a1 since a1 is appl scope.
none scope bean in s1 is available only until s1 is not destroyed and when s1 is created
again n1 is instanciated and made available to it.
Is it correct?
and what the purpose of using it? only to avoid creating such bean our self?
many thanks
A bean with a <managed-bean-scope> of none or a #NoneScoped annotation will be created on every single EL expression referencing the bean. It isn't been stored by JSF anywhere. The caller has got to store the evaluated reference itself, if necessary.
E.g. the following in the view
<p>#{noneScopedBean.someProperty}</p>
<p>#{noneScopedBean.someProperty}</p>
<p>#{noneScopedBean.someProperty}</p>
on a none-scoped bean will construct the bean 3 (three) times during a request. Every access to the bean gives a completely separate bean which is been garbaged immediately after the property access.
However, the following in for example a session scoped bean
#ManagedProperty("#{noneScopedBean}")
private NoneScopedBean noneScopedBean;
will make it to live as long as the session scoped bean instance. You should only make sure that you access it in the view by #{sessionScopedBean.noneScopedBean.someProperty} instead.
So it may be useful when you want scope-less data being available as a managed property in an arbitrary bean.
I'm using #nonescoped when my "view logic" dont need to be in any scope but be referenced by another ManagedBean.
I'm working with Liferay, as I want to make my architecture and design independent of liferay, I create my services interfaces and Dto, but when you need to persistence data, Liferay need that the companyId and companyGroupId be sended from the view layer (in this case JSF).
To maintain independence, I did a "Adapter pattern" creating a ServiceLayer ManagedBean with #noneScope with an interface independent from Liferay. This way I can get the companyId and the companyGroupId needed by the Liferay Apis.
The advantage of using #noneScope is that you can use it as a #ManagedProperty in any bean of any scope.
#NoneScoped would be beneficial in the following scenario.
Assume that we have to inject the same bean in two different scoped beans, we can mark that bean as #NoneScoped. Say a bean BeanOne with #NoneScoped can be easily injected in any bean with any scope like #Request or #Session.
Without using #NoneScoped for BeanOne, we may have to duplicate the bean with different scopes and inject them accordingly.

Canonical way to obtain CDI managed bean instance: BeanManager#getReference() vs Context#get()

I figured that there are two general ways to obtain an auto-created CDI managed bean instance via BeanManager when having solely a Bean<T> to start with (which is created based on Class<T>):
By BeanManager#getReference(), which is more often shown in
snippets:
Bean<TestBean> bean = (Bean<TestBean>) beanManager.resolve(beanManager.getBeans(TestBean.class));
TestBean testBean1 = (TestBean) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));
By Context#get(), which is less often shown in snippets:
Bean<TestBean> bean = (Bean<TestBean>) beanManager.resolve(beanManager.getBeans(TestBean.class));
TestBean testBean2 = beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean));
In effects, they do ultimately exactly the same thing: returning a proxied reference to the current CDI managed bean instance and auto-creates the bean instance if it doesn't already exist in the scope.
But they do it a bit differently: the BeanManager#getReference() always creates a whole new proxy instance, while the Context#get() reuses an existing proxy instance if already created before. This is evident when the above code is executed in an action method of an existing TestBean instance:
System.out.println(testBean1 == testBean2); // false
System.out.println(testBean1 == this); // false
System.out.println(testBean2 == this); // true
The javadoc of Context#get() is very explicit in this:
Return an existing instance of certain contextual type or create a new instance by calling Contextual.create(CreationalContext) and return the new instance.
while the javadoc of BeanManager#getReference() is not explicit enough on this:
Obtains a contextual reference for a certain bean and a certain bean type of the bean.
This got me confused. When do you use the one or the other? For the both ways you need a Bean<T> instance anyway, from which the bean class and bean scope is readily available which is required as additional argument. I can't imagine why they would need to be supplied externally in this specific case.
I can imagine that Context#get() is more memory efficient as it doesn't unnecessarily create another proxy instance referring the very same underlying bean instance, but just finds and reuses an existing proxy instance.
This puts me to the following question: when exactly is the BeanManager#getReference() more useful than Context#get()? It's more often shown in snippets and more often recommended as solution, but it only unnecessarily creates a new proxy even when one already exists.
beanManager#getReference gives you a new instance of a client proxy but the client proxy will forward method calls to the current contextual instance of a particular context.
Once you obtain the proxy and keep it and the method calls will be invoked on the current instance (e.g. current request).
It is also useful if the contextual instance is not serializable - the client proxy will be and will reconnect after you deserialize it.
BeanManager#getContext obtains the target instance without a client proxy. You may still see a Weld's proxy in the class name but that is an enhanced subclass that provides interception and decoration. If the bean is not intercepted nor decorated this will be a plain instance of the given bean.
Usually (1) is more suitable unless you have a special use-case where you need to access the target instance directly (e.g. to access its fields).
Or in other words
1) BeanManager#getReference will return a 'Contextual Reference', with a normal scoping proxy for the bean.
If a bean have with #SessionScoped as
#SessionScoped User user;
Then the contextual reference user will 'point' to the respective User instance (the 'Contextual Instance') of the current session for each invocation.
Two different invocations to user.getName() from two different web browsers will give you different answers.
2) Context#get() will return a the internal 'Contextual Instance' without the normal scoping proxy.This is usually nothing a user should call himself. If you get the User user for "Bob" that way and store it in an #ApplicationScoped bean or in a static variable,
then it will always remain to be the user "Bob" - even for web requests from other browsers! You will get a direct, non-proxied instance.
I have a Singleton that I was using the getReference() method to get the reference to. Even though the singleton was already initialized, the proxy created through getReference() called the #PostConstruct each time getReference() was used.
#Startup
#ApplicationScoped
#Singleton
#PostConstruct
private void initialize() {}
By switching to the getContext().get() method, the unnecessary #PostConstruct proxy calls are no longer made.
This was very helpful when integrating CDI with javafx, the thing was that I needed a reference to the right scoped object cause and not the proxy of the dependent scope...
I used a producer method to get a javaFX Node that gets injected into the controler like so:
#Inject
#ApplicationScoped
#FXMLFile("javafx/wares.fxml")
#FXMLController(WaresController.class)
Parent wares;
but when using the BeanManager#getReference() the proxy I get back "eats" all the values that are set by the FXMLLoader, the getContext.get() way solved it.
Thnx for this

Basic question about backing beans for Composite Components

I can't find any guidance on this question. I am writing a composite component that needs its own backing bean because it interacts with a data base.
The new component also needs to be able to set a value in some other backing bean as the result of some user action.
To do this, the question is do I have to write a #FacesComponent java class or a regular #Model/#Named (I use CDI annotations) type of bean? If you can use either, what is the advantage of one or the other?
Secondary question: will I be able to use CDI #Inject into a #FacesComponent to get my DAOs and such?
Update: I discovered that I can access cc.attr objects with the following code in a regular backing bean:
FacesContext fc = FacesContext.getCurrentInstance();
Object obj = fc.getApplication().evaluateExpressionGet(fc,
"#{cc.attrs.model.location}", Location.class);
So this allows me to obtain attributes. I haven't found out how I can write them yet.
So it seems that the only real reason to do a #FacesComponent is if you want to write rendering code that will output something the normal Facelets tags won't render. Is this correct?
I think BalusC responded to this basic question in this thread.
The main advantage is the ability of a #FacesComponent to access attributes that a UIComponent normally has access to, rather than trying to tie in with EL expressions executed in the bean.

Resources