How does business logic class calls methods inside a managed bean? - model-view-controller

I have some business logic code that renders some facesMessages on the facelet based on its output, so i made a method in the facelet managed bean like this method:
public void renderFacesMessages(String summary, String detail) {
FacesMessage message = new FacesMessage(summary, detail);
FacesContext.getCurrentInstance().addMessage(null, message);
}
and the business logic class will pass arguments to this method according to the message that's needed, the question is what is the right approach for business logic to call this method on the managed bean?

It is all about the Layering Concept...
I presume you have a ManagedBean which has a method that will delegate the business logic to a seperate Business Class/Module.
If this is the case,I would tell you ,NEVER have any Faces Methods on the Business Side...
Instead have the Business Results wrapped in a Class and return back to Managed Bean.This Result Class will encompass the Results,Meta information about the Result like,Errors,Exceptions.So now your managed Bean can use the renderFacesMessage method
Even if you had not followed the above presumption:My Suggestion
Never have JSF Faces Logic inside Business Components.It will be a bad Idea.

Don't let the business logic call a JSF backing bean.
Instead let the backing bean call the business logic (eg an EJB bean or a transactional CDI bean in Java EE 7), then depending on the result of this call (exception, return value, etc) generate Faces messages and/or redirect to a new page etc.

As the businesslogic will be stateless (I guess/hope so), I would say that you should let the managed bean which called your businesslogic handle the error message display, by catching an exception e.g.
On the other hand, you can pass the managed bean to the businesslogic (or better, just an interface of the managed bean), so the businesslogic can callback the managed bean. But i would prefer the first approach.

Related

Spring: new() operator and autowired together

If I use Spring, which of these two methods is more correct.
Can I use the new() operator even if I use dipendency injection?.Can I mix both?
I would like to have some clarification on these concepts.
Thanks
First method:
#RequestMapping(method=RequestMethod.GET)
public String create(Model model){
model.addAttribute(new User());
return "index";
}
Second Method:
#Autowired
User user;
#RequestMapping(method=RequestMethod.GET)
public String create(Model model){
model.addAttribute(user);
return "index";
}
By using dependency injection does not mean that the use of new operator is automatically prohibited throughout your code. It's just different approaches applied to different requirements.
A web application in spring is composed of a number of collaborating beans that are instantiated by the framework and (unless overriding the default scope) are singletons. This means that they must not preserve any state since they are shared across all requests (threads). In other words if you autowire the User object (or any other model attribute), it is created on application context initialization and the same instance is given to any user request. This also means that if a request modifies the object, other requests will see the modification as well. Needless to say this is erroneous behavior in multithreaded applications because your User object (or other model attribute) belongs to the request, so it must have the very narrow scope of a method invocation, or session at most.
You can also have spring create beans with different scopes for you, but for a simple scenario of a model attribute initialization, the new operator is sufficient. See the following documentation if interested in bean scopes : Bean scopes
So in your use case, the second method is totally wrong.
But you can also delegate the creation of your model attributes to spring if they are used as command objects (i.e. if you want to bind request parameters to them). Just add it in the method signature (with or without the modelattribute annotation).
So you may also write the above code as
#RequestMapping(method=RequestMethod.GET)
public String create(#ModelAttribute User user){
return "index";
}
see also : Supported method argument types
If you want your beans to be "managed" by Spring (for e.g. to use with Dependency Injection or PropertySources or any other Spring-related functionality), then you do NOT create new objects on your own. You declare them (via XML or JavaConfig) and let Spring create and manage them.
If the beans don't need to be "managed" by Spring, you can create a new instance using new operator.
In your case, is this particular object - User - used anywhere else in code? Is it being injected into any other Spring bean? Or is any other Spring bean being injected in User? How about any other Spring-based functionality?
If the answer to all these questions is "No", then you can use the first method (create a new object and return it). As soon as the create() method execution is complete, the User object created there would go out of scope and will be marked for GC. The User object created in this method will eventually be GC-ed.
Things can be injected in two ways in a Spring MVC applications. And yes, you can you can mix injection and creation if doing right.
Components like the controller in your example are singletons managed by the application context. If you inject anything to them it is global, not per request or session! So a user is not the right thing to inject, a user directory can be. Be aware of this as you are writing a multithreaded application!
Request related things can be injected to the method like the used locale, the request, the user principal may be injected as parameters, see a full list at Spring MVC Documentation.
But if you create a model attribute you may use new() to create it from scratch. I will not be filled by spring but to be used by your view to display data created by the controller. When created in the request mapped method that is ok.

Spring Custom Scoped Bean - Destruction Callback

I have created a custom scope in my application that implements org.springframework.beans.factory.config.Scope.
As part of this, i have to implement the method below so that the PreDestroy method gets correctly invoked on my custom scoped beans.
public void registerDestructionCallback(String name, Runnable callback) {
}
The javadocs on the method are not that clear and I seem to be lost about what code i should write in that method.
Can someone please help?
It depends on what your custom scope actually does and if you are using this scope for DisposableBean, beans with destroy-method, and DestructionAwareBeanPostProcessor.
In simplest case you don't need to do anything or just log a warning that callback is not supported.
In more complex case, you need to handle object destruction that is outside of regular custom scope life cycle. Eg. when object is destroyed, based on its expiration or something similar (unlike explicit call to Scope.remove(String name) method).
For example, for session-scoped beans, this callback is hooked up to HttpSessionListener.sessionDestroyed(..) event. See sources for org.springframework.web.context.request.SessionScope class.

JSF multiple calls to getter causing service timeout

I am using JSF and spring . I have a spring managed bean in session scope. I am getting a quite big list from a service call . I am calling the service and getting the list In the getter which is bind to the jsf view. when I run the app the getter is called multiple times.
so before the list is returned it is invoked again and it times out.
The list is dynamic I need to get fresh list on page load and every minute the list is refreshed using richfaces a4j poll . The list has to be retrived everytime from database.
If I change the bean to request scope and move the service call to the constructor the performance is worse.
can anyone suggest a better archetecture to do this ?
JSF managed bean getters should absolutely not call services. They should just return the managed bean property. This property should be already prepared by a (post)constructor or (action)listener method. Those methods will be invoked exactly one time. Getters will be invoked multiple times as JSF needs to access the value.
You need to rewrite your code as such that the first-time job is done in the (post)constructor of the managed bean and that the <a4j:poll> invokes a listener method which refreshes the list and that the getter does absolutely nothing else than just returning the property.
Here's a basic kickoff example using the standard Java EE 6 artifacts. I don't do Spring, but you should be able to supplant this with Spring artifacts.
#ManagedBean
#SessionScoped
public class Bean {
private List<Entity> entities;
#EJB
private EntityService service;
#PostConstruct
public void load() {
entities = service.list();
}
public List<Entity> getEntities() {
return entities;
}
}
with
<a4j:poll action="#{bean.load}" interval="60000" render="someTableId" />
See also:
Why JSF calls getters multiple times
Unrelated to the concrete problem: if you have a rather large DB table (>1000 rows) then copying the entire DB table into Java's memory is a pretty bad idea. Implement pagination/filtering.

What is the difference between BeanPostProcessor and init/destroy method in Spring?

What is the difference between implementing the BeanPostProcessor interface and either using the init/destroy method attributes in the XML configuration file in Spring or implementing InitializingBean/DisposableBean interface?
This is pretty clearly explained in the Spring documentation about the Container Extension Points.
The BeanPostProcessor interface defines callback methods that you can
implement to provide your own (or override the container's default)
instantiation logic, dependency-resolution logic, and so forth. If you
want to implement some custom logic after the Spring container
finishes instantiating, configuring, and initializing a bean, you can
plug in one or more BeanPostProcessor implementations.
So in essence the method postProcessBeforeInitialization defined in the BeanPostProcessor gets called (as the name indicates) before the initialization of beans and likewise the postProcessAfterInitialization gets called after the initialization of the bean.
The difference to the #PostConstruct, InitializingBean and custom init method is that these are defined on the bean itself. Their ordering can be found in the Combining lifecycle mechanisms section of the spring documentation.
So basically the BeanPostProcessor can be used to do custom instantiation logic for several beans wheras the others are defined on a per bean basis.
Above answers clearly explains some of the very important aspect.
Apart from that it's also important to understand that both beanPostProcessor and init and destroy methods are part of the Spring bean life cycle.
BeanPostProcessor class has two methods.
1) postProcessBeforeInitialization - as name clearly says that it's used to make sure required actions are taken before initialization. e.g. you want to load certain property file/read data from the remote source/service.
2) postProcessAfterInitialization - any thing that you want to do after initialization before bean reference is given to application.
Sequence of the questioned methods in life cycle as follows :
1) BeanPostProcessor.postProcessBeforeInitialization()
2) init()
3) BeanPostProcessor.postProcessAfterInitialization()
4) destroy()
You may check this by writing simple example having sysout and check their sequence.
Init and Destroy callback methods are part of Spring bean life cycle phases. The init method is going to be executed after bean instantiation. Similarly, The destroy method is going to be executed before bean finalization.
We can implement this functionality using implementing interfaces InitializingBean and DisposableBean, or using annotations #postconstruct and #predestroy, or declare the <bean> with init-method and destroy-method attributes.
BeanPostProcessor interface is used for extending the functionality of framework if want to do any configuration Pre- and Post- bean initialization done by spring container.
For Example: By default, Spring will not aware of the #PostConstruct and #PreDestroy annotation. To enable it, we have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean configuration file. Here CommonAnnotationBeanPostProcessor is predefined BeanPostProcessor implementation for the annotations. Like:
#Required enables RequiredAnnotationBeanPostProcessor processing tool
#Autowired enables AutowiredAnnotationBeanPostProcessor processing tool
And one more main diff is InitializingBean,DisposableBean related afterPropertiesSet() & destory() methods did not accept any paratmeters and return type also void, so we did not implement any custom logic.
But coming to BeanPostProcess methods postProcessBeforeInitialization(Object bean,String beanName) and postProcessAfterInitilization(Object bean,String beanName) are accept those two paramaters and return type also Object so we are able to write initilzation logics as well as any custom login based on the passing bean...
These both callback method feautes are including the bean life cycle and the following are the life cycle as follows
1) BeanPostProcessor.postProcessBeforeInitilazation()
2) #postConstruct or InitializingBean.afterPropertiesSet() or initialization method which is
defining in xml /* here also it's following the same oredr if three ways are availiable **/
3) BeanPostProcessor.postProcessAfterInitialization()
4) #preDestroy or DisposibleBean.destroy() or destroy method which is defining in xml
/* here also it's following the same oredr if three ways are availiable **/
Just a short supplement to all the answers above: If you have any generic logic, common logic that needs to be universally applied to all your Spring beans, such as the injection of a logger to your beans, setting of a properties file, setting default values to fields of your beans through reflection; you could put that logic into ONE single place: the #Overriden callbacks (eg: postProcessBeforeInitialization(Object arg0, String arg1) if you are implementing the BeanPostProcessor interface); instead of duplicating the same logic across all your beans.
a)The postProcessBeforeInitialization() will be called before initialization of the bean.
b)Once the bean gets initialized, the different callbacks methods are called in the following order as per the Spring docs:
Methods annotated with #PostConstruct
afterPropertiesSet() as defined by the InitializingBean callback interface
init method defined through the XML.
The main difference is that the above 3 methods get called after the initialization get completed by the postProcessBeforeInitialization() method.
Once these methods get completed the method postProcessAfterInitialization() will be called and then the destroy methods are called in the same order:
Methods annotated with #PreDestroy
destroy() as defined by the DisposableBean callback interface
destroy() method defined through the XML.

Spring destroy-method & half injected objects

In spring I often find myself utilizing the init-method & destroy-method attributes on beans. I'm curious about the contract of these methods. The init-method attribute seems to be called post construction and after all properties have been set. My question is if destroy-method has the same contract. If a setter throws for whatever reason, and the object doesn't have all its properties set, spring won't call the init-method, but I can't find any documentation about spring calling the destroy-method in this situation.
If it does obviously checks for null have to be in place, I'm curious what others do in this situation.
I did a simple test and I found out that in case of a setter throwing an exception both the init and the destroy methods won't be called.
I believe that this is the logical thing to do. A setter shouldn't be allowed to fail - if it does, there is nothing the framework can do to help you. The only reaction to this kind of error is to correct the setter. So I think that your question is irrelevant. Half injected objects shouldn't be allowed.
If you know that a setter could throw an Exception, you should catch it and set a reference to null or do whatever else is appropriate.
The Spring code of interest here is AbstractAutowireCapableBeanFactory.doCreateBean() (I'm looking at the Spring 3 M4 source, but it should be essentially the same for Spring 2.5). The the last thing this method does is register the bean for disposal, and it only does that if the rest of the method (including instantiation and initialization) succeeds. So if any part of the bean initialization fails, the destroy-method callback won't be invoked.

Resources