How to store a bean per conversation - java

Is there a way to store some bean inside the conversation context? I.e for each new conversation, a new separate bean is created belonging to it.

The easiest way to do what you want is to declare a ConversationScoped managed bean or EJB where JSF2 manages the scope.
There are some good explanations here:
http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html
http://www.ibm.com/developerworks/java/library/j-jsf2fu-0710/index.html#cdi
http://www.theserverside.com/tip/Dependency-Injection-in-Java-EE-6-Conversations-Part-4
http://www.andygibson.net/blog/article/cdi-conversations-part-1/
http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/
http://blog.goyello.com/2011/06/08/jee6-cdi-and-conversation-scope/
... any of which will do a better job than I will. The very short version is that you annotate a bean - which can be a plain POJO that follows the bean conventions - with the #ConversationScoped annotation. You then #Inject a Conversation object, which you can use to begin() and end() conversations. Inject this #ConversationScoped bean into other things. The Conversation.begin and Conversation.end methods control its lifecycle.
There's a bit much code to just post here, but the above links should help.
An alternative to #ConversationScoped POJO managed beans can be #Stateful #ConversationScoped EJBs. They can be really handy when you need EJB services in a conversation.
For some of the conceptual background and detail read the CDI/Weld reference on scopes - and the rest of the CDI/Weld manual. It's really well written and really good.

Related

why spring does not manages prototype bean once created

So regarding prototype scoped bean, I know spring just crate it do life cycle process before handover it to requested bean. and then if forgot it.And also logically I can understand that since it is prototype, it will be used by per request only (yes not http request.) But why not spring container just keep reference of prototype bean just to manage complete life cycle?
A "prototype" scope behaves pretty much just like any object POJO created with the "new" operator, except for the Spring prototype will have #Autowired beans connected up. The aren't singletons, or connected to sesssion or request scope, so they are just more similar to a regular POJO.

How to register an existing bean in Application context and what is the advantage I get out of it?

I am a newbie to Spring. I was going through spring documentation where it says we can register existing objects created outside spring container in application context. I did that like this
OutsideBean outsideBean = new OutsideBean();
ConfigurableApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring.xml");
// SpringBean is the bean which is defined in spring.xml
SpringBean springBean = applicationContext.getBean("springBean", SpringBean.class);
ConfigurableListableBeanFactory configurableListableBeanFactory =
applicationContext.getBeanFactory();
configurableListableBeanFactory.registerSingleton("outsideBean", outsideBean);
I have many unanswered questions here.
The way I am doing above, is it correct.?
Even if it is correct, is it the best way to do that.?
What if I have to register a bean as a 'prototype'.?
By registering my bean in application context what is the advantage I get out of it.?
I read through many links in stackoverflow but couldnt understand it. Hence asking it in new thread.
AFAIK, yes
No, it's not the best way. The best way is to create the context from a Spring configuration class, and to create beans in this configuration class, using #Bean annotated methods, as described in the documentation. Or simply by annotating your class with #Component and letting Spring find your bean by classpath scanning.
Your specify a scope using the #Scope annotation
The advantage is that the bean is managed by Spring, and can thus be injected by Spring in all the other beans. It can also be injected by any other bean. And it can benefit from AOP in order, for example, to provide transactional methods.
Well prasad, to understand what is applicationcontext / bean / what will you get out of it you need to go through the basic architecture of Spring framework, Spring literally stands out when compared other java frameworks, as its DI (Dependency Injection) & IOC (Inversion of control) container features.
Rod Johnson laid the foundation for Spring in his Expert One-on-One J2EE Design and Development (http://as.wiley.com/WileyCDA/WileyTitle/productCd-0764543857.html) way back in 2002. Which suggested framework specific free POJO's power to enhance modern enterprise application developement.
Kindly go through foll. link, to know about DI & IOC.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html
TO answer your questions.
The way I am doing above, is it correct
Well technically what you did will work definitely. But Spring provides no. of combination to define a object as a bean.
Even if it is correct, is it the best way to do that.?
I suggest you define all your beans in XML document or annotate the class which u want as a bean with #Component annotation or you can omit XML file do away everything with Java configuration file (which i have not really tried).
What if I have to register a bean as a 'prototype'.?
Can you please elaborate what u mean by Prototype
By registering my bean in application context what is the advantage I get out of it.?
If you understand the essence of DI u will easily answer this question by yourself. As mentioned earlier for DI spring provides IOC factory called BeanFactory (its an interface go thorough docs, there are many implementation BeanFactory, ApplicationContext is one of them). So if you configure a object as a bean u can ask factory to give to u at any no of times with its properties are again loosely coupled with one or more beans in container.

Is it permitted to use #Stateful and #javax.faces.view.ViewScoped together?

My understanding is that
#Stateful
#ConversationScoped
is allowed, and is normal usage.
With the new JSF 2.2 ViewScoped (javax.faces.view.ViewScoped) annotation, which is documented to be fully compatible with CDI scope annotations, does this mean that:
#Stateful
#ViewScoped
Is a viable combination?
#Stateful is an EJB annotation, so technically your bean will be a stateful EJB bean, not a CDI bean. And it will only work in a full-blown application server.
In case of (only) JSF 2.2 + CDI use:
#javax.inject.Named // to expose a bean in the EL context
#javax.faces.view.ViewScoped // to make it view scoped
Also don't mix up the latter annotation with #javax.faces.bean.ViewScoped, it once took me a while to find the issue.
There's a nice example.
keep in mind that with #stateful, every time you inject it you will get a new concrete instance, because you're indicating storing state with that annotation. also the EJB layer concept of session is not the same as the JSF layer concept of session, and confusing the two can create all sorts of issues for you.
JSF session is tied to a specific client maintained by either a cookie or url-rewriting (container configuration).
EJB session is tied to a specific method execution (#Stateless) or a concrete instance (#Stateful).
unless you need to have durable serialization and state maintenance within the EJB, stateful is not going to give you want you want. you're best bet will be to separate the transactional aspects into a #Stateless and store your state in a #ViewScoped that gets passed into the #Stateless methods.

How is dependency injection working?

I am reading the Pro Spring 2.5 book and I have a question to how dependency injection works.
I understand the BeanFactory and doing dependency lookups. Now I read about dependency injection and I have some questions. Based on what I understand you want to limit the lookups to the minimum such as looking up an object for boot strapping the application. Then dependency injection will take care of the rest. However I don't understand this works.
Let say you have a beanfactory, you get an MyApplication instance that starts the whole application. The rest of the objects use dependency injection to get their collaborators. The beanfactory maintains the list of beans it manages but isn't this factory only available in the main method of the application? And if the beanfactory also manages the scope of their containing beans I don't understand how that is done. Are the beanfactory global in some way?
The bean factory instantiates all objects. It parses your configuration (xml or annotations), instantiates your beans and sets their dependencies. Then all these beans are stored in the application context.
You usually have an entry point to your application - there you do context.getBean(..). Now that bean has its dependencies injected, because it is put in the context by the bean factory.
The rule of thumb that will probably clear things: you never use the new operator (with bean classes) when using a DI framework. The framework makes the instances, not you.
So, there are two ways this can happen (as of Spring 3). In "traditional" dependency injection, the bean factory can only inject dependencies into beans it creates itself. In this scenario, the bean factory will resolve and inject all dependencies of a bean when that bean is first created.
The other way requires you to employ "full" AspectJ with either load- or compile-time weaving. In this scenario, you use an aspect in the spring-aspects.jar that basically pointcuts all new operations, allowing you to get dependency injection in arbitrarily created objects. This is triggered by using the #Configurable annotation. You can read more here.
The whole point on inversion of control and dependency injection is that you (typically) don't need the beanfactory except to get your application started. Your dependencies "automatically appear" in your objects. This is basically intended for objects with very few, typically one, instance during the whole lifetime of your application.
E.g. if your MyApplication depends on an instance of MyModuleA, you can simply have it #Autowired. When you fetch the application object from beanfactory at start time it already comes with an instance of MyModuleA preset.
About the scopes: this comes from web context. Besides objects with only one instance ever you can have objects scoped to a user's session. There you can store information you need to keep over several requests but separate for different users, think: shopping cart.
Typically treat the bean factory as global. I think it would be possible to have several instances, but they would be disconnected and can't inject objects only known to other instances.

What's the point of using #Scoped with EJBs?

Usually I'm using #RequestScoped or #SessionScoped (from javax.enterprise.context) to inject objects (for instance in faces beans) using #Inject.
I am also using EJBs. As I understood, a set of stateless EJB copies (pool) is used to be injected to objects. The reason there are many copies is to ensure one instance of EJB isn't accessed concurrently. When speaking about stateful EJBs (again as I understood), one instance of such is bound to concrete injection point. And they are injected using #EJB (the stateless ones too).
Frequently I can see on the web examples of using #Stateless or #Stateful in conjunction with #Scoped. What is the meaning of them?
Edit: (trying to clarify as no one responded to this moment):
I'm especially interested whether such scoped annotations change anyhow (and if they - how) moment of creation of EJB's instance.
For my understanding: if I have, #EJB annotated field, object of proper class is injected there. If such EJB is stateless, container simply take free instance from the pool of pre-created instances. Pool can be resized if necessary. It is stateless, because object isn't guaranteed to be preserved across method calls of our class (i.e. class which has field containing reference to EJB).
We can also use stateful EJB and in that case one instance is preserved during method calls. As I think, it will be simply injected once per object creation. (There is also singleton EJB, which is shared between all objects).
I can't find the purpose of #Scoped annotations for EJB here.
Edit 2:
One can use such combination of annotations if class is to be injected via EJB and DI (by #Inject) mechanisms. This is rather, however, special case and not elegant. I am asking if you know any other reasons.
Edit 3:
Please see my comment under arjan's answer.
A #Stateless or #Singleton bean may be explicitly scoped to prevent its scope being automatically modified to a scope that may be illegal. E.g. both these bean types are not allowed to be #RequestScoped. See this link for some more info: http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html/CDI.html
#Stateful makes a lot of sense to be (explicitly) scoped. Namely, without a scope you as a programmer have to take care to call the #Remove annotated method. This can be troublesome to guarantee, since such a bean is typically not used in a single method where you can call the #Remove method in a finally block. With a scope, the bean is exactly removed when the scope ends.
Furthermore, without a scope you can't always use injection to obtain a reference to a stateful bean's stub. Namely, every time the injection happens, you'll get a new instance. This is particularly troublesome when injecting a stateful bean in a request scoped (JSF) backing bean, where you have the intent to preserve the stateful bean across a couple of requests.
Then, in combination with #Named, you can also use a session bean directly as a backing bean to flatten your application layers (see e.g. http://jaxenter.com/java-ee-6-overview-35987-2.html). Obviously you want an explicit scope in that case. Now flattening your layers may not be a best practice in larger applications, but for smaller applications and/or people just beginning with Java EE there is definitely a wish to put business logic directly into the backing bean. It's then required that backing beans have access to the same kind of services (mainly transactions) that 'business beans' normally have.
Finally, Gavin King (CDI spec lead) has suggested to always use #Inject instead of #EJB. The only exception concerns remote EJBs, where #EJB is still used.
Part of the confusion around EJB and CDI is that CDI is a new component model in Java EE and still relatively new. Although they integrate fairly well with each other, they are still two different component models and not all best practices have been thought out yet. Reza Rahman (EG member, EJB book writer, and author of CDI implementation CanDI) has suggested that the EJB model could possibly be retrofitted in the future as a set of CDI services. Indeed, in Java EE 7 a step is being made by separating the transactional services from EJB and making them available via (CDI) annotations.

Categories