What is the difference between #ApplicationScoped and #Singleton scopes in CDI? - java

In CDI there is the #ApplicationScoped and the (javax.inject) #Singleton pseudo-scope. What is the difference between them? Besides the fact that #ApplicationScoped is proxied, and #Singleton is not.
Can I just change my #Singleton bean to #ApplicationScoped? Can #ApplicationScoped bean have two (or more) instances?

#Singleton is not part of the CDI specification. It is part of EJB and javax.inject (JSR-330). It is not mentioned in the spec what is its behaviour, so you can only rely on what's written in the Weld documentation.

in short: You can even mix it (#Singleton and #ApplicationScoped) and it makes sense in some scenarios.
(and works as expected in mine!)
Additionally to the other answers so far I'd like to add some more points for clarification in real world scenarios.
For me this question developed out of How do I force an application-scoped bean to instantiate at application startup?
In some discussion there I stated this and can't find a valid argument against it so far:
In a lot of real-life scenarios/setups I would say it's hard to
definitely say - from an abstract/modelling point of view - whether
something is (or will become/be treated like) an EJB or an application-scoped managed bean.
(debatable but not conclusive) arguments (from my point of view) against it so far:
(#BalusC and all others: I'd like to see them beeing conclusive, but if not, the above may hold true and nevertheless the arguments may still help the reader to get the differences/advantages/disadvantages/ bad/good practices)
EJB vs. Managed Bean
BalusC: That's an EJB not a managed bean, which is quite different. EJBs run in backend and managed beans in frontend. EJBs run in transactional context too.
[...] You just confused enterprise beans with managed beans and I just pointed out that.
but:
me: I think you are not quite correct and overstating the meaning/usage and it looks debatable to me. http://en.wikipedia.org/wiki/Enterprise_JavaBeans
Enterprise JavaBeans (EJB) is a managed, server software for modular construction of enterprise software, and one of several Java APIs. EJB is a server-side software component that encapsulates the business logic of an application.
Types of Enterprise Beans
Session Beans [3] that can be either "Stateful", "Stateless" or "Singleton" [...]
Message Driven Beans [...]
... which still holds true in my case.
Singleton EJB vs. Application Scoped Bean
Locking
BalusC: A singleton EJB isn't the same as an application scoped bean. A singleton EJB is read/write locked and thus potentially inefficient/overconvoluted for the task you had in mind. Long story short: Grab a good Java EE book and learn to use the right tool for the job. One way definitely isn't the other way. That it works doesn't mean that it's the right tool. A sledgehammer is capable of fastening a screw, but it isn't necessarily the right tool to that :)
but:
(I can't see the sledgehammer here - sorry ...)
It's good to know the locking defaults (I was not aware of it), but this seems to be incorrect again: Oracle Java EE 6 Tutorial on Managing Concurrent Access in a Singleton Session Bean
When creating a singleton session bean, concurrent access to the singleton’s business methods can be controlled in two ways: container-managed concurrency and bean-managed concurrency.
[...]
Although by default, singletons use container-managed concurrency, the #ConcurrencyManagement(CONTAINER) annotation may be added at the class level of the singleton to explicitly set the concurrency management type

Usually when you want to have only one instance of some object you probably should use #ApplicationScoped annotation - such object is proxied and thus can even be properly serialized out-of-the-box.
On the other hand, there are also many cases, where you want only one instance of the class, but such class cannot be proxied (e.g. because of being final) - then #Singleton is a rescue. Because Singleton is a pseudo-scope and is not being proxied like any "normal" scope.

#Singleton in JSR-299 refers to Singleton session beans (javax.ejb.Singleton, not javax.inject.Singleton), not JSR-299 managed beans in a built-in scope called Singleton.
You might find in your server that #ApplicationScoped is one-per EAR or one-per WAR/EJB-JAR as it is not clear in the specification, but you should definitely not expect it to be one per JVM.

There is one more difference:
#Singleton is not bean defining annotations, as the Singleton scope is not a normal scope.
Then #ApplicationScoped is bean defining annotations.
With CDI 1.1 spec: When application in discovery-mode = annotated, Weld does not identify beans with #Singleton and not loaded this

One of the major differences that you can write your class with default constructor has private access modifier when using javax.inject.Singleton, but your class should have default constructor with at least default access modifier when using javax.enterprise.context.ApplicationScoped and this is JBOSS 6.1 GA Final implementation

Related

Problem in reading Spring framework doc: injecting bean to Spring at runtime

I can not understand the following documentation sentence
(...) the registration of new beans at runtime (concurrently with live
access to the factory) is not officially supported and may lead to
concurrent access exceptions, an inconsistent state in the bean
container, or both.
I understand that it can't be injected at runtime, but previously we can read in the documentation:
In addition to bean definitions that contain information on how to
create a specific bean, the ApplicationContext implementations also
permit the registration of existing objects that are created outside
the container (by users). This is done by accessing the
ApplicationContext’s BeanFactory through the getBeanFactory() method,
which returns the BeanFactory DefaultListableBeanFactory
implementation. DefaultListableBeanFactory supports this registration
through the registerSingleton(..) and registerBeanDefinition(..)
methods.
So how to implement this form of injection, not at the runtime. Now I'm confused.
I might not be the right person to answer this, but I would like to give a link where it has been answered beautifully, take a look might be the similar thing you asking.
bean injected dynamically

Local stateless EJBs vs Remote

I'm kind of a newbie in EJBs,but I've been given an EJB tier to improve.
This tier consists of an EJB wich exposes the operations available:
#Stateless(name = "myejb")
public class Facade implements FacadeRemote
{
#EJB
private EntityAHomeLocal entityAHome;
#EJB
private EntityBHomeLocal entityBHome;
// methods signatures and implementations
}
As you can see this EJB use other local EJBs that manage operations on entities.
#Stateless
public class EntityAHome implements EntityAHomeLocal
{
#PersistenceContext(name="myUnit")
private EntityManager manager;
// methods signatures and implementations
}
I'm having hard time to fully understand the architecture of this tier.
Is this kind of architrcture common ?
Are local stateless EJB managed throught a pool of instances just like remote stateless EJBs ?
Would it still work even if entityAHome and entityBHome were remote EJBs ?
Strictly speaking, the spec only says stateless beans are "typically" pooled (section 4.3.10.2), so the behaviour for local beans is vendor-specific, but in practice I believe all the major vendors do (for example).
Local and remote interfaces are almost entirely interchangeable, but with extra deployment restrictions (i.e. they must be deployed locally, of course), and some calls to local interfaces use pass-by-reference semantics, whereas remote interfaces always use pass-by-value (link).
I can't see anything that would stop that code working with remote interfaces, although I think some of the naming is confusing - a session bean (#Stateless) is different from an entity, and in EJB terminology "home" refers to a kind of factory class, which I don't think is your intention here (?). Also, be aware that switching to #Remote can add a performance overhead, as the second link notes.

What does it mean to "proxy a bean"?

At work and online I keep hearing the term "proxy" with respect to enterprise Java development. For example, metrics-spring uses this phrase:
This module does the following things:
Creates metrics and proxies beans which contain methods annotated with
#Timed, #Metered, #ExceptionMetered, and #Counted [emphasis mine]
I'm unfamiliar with a lot of the language in the Java ecosystem of frameworks and libraries. I feel like I have a good understanding of what a bean is, but I'm still not clear about how one would proxy a bean.
What does it mean to proxy a bean?
Typically, you have a bean like
Bean bean = new Bean(); // actually created by the context
With this, you can do anything that the Bean class declares as behavior (invoke its methods).
There are times where it would be nice if you could, for example, track how long a method invocation takes.
You could do
long start = .. // get start time
bean.invoke();
long end = .. // get end time
// end - start
But doing this for each method invocation sucks. So, instead, patterns, architectures, and styles like Aspect Oriented Programming exist.
Instead of the Bean above, you'd have
Bean bean = new TimingBean(new Bean()); // again done by the context
where the TimingBean is a proxy type that extends and implements all the types that Bean extends and implements. For all intents and purposes it is a Bean, but it adds a bunch of additional behavior before delegating each invocation to the Bean object. In this case, it would track how long each of Bean's method's took to execute.
Basic Spring uses JDK proxies and CGLIB proxies. Here are some differences between them.
It uses this for its scheduling and asynchronous invocations. It uses it for transactional support with databases. It uses it for caching. It even uses it for its Java based container configuration.
Proxying means that your client code thinks it's talking to one bean, but a proxy is really doing the listening and responding.
This has been true since early distributed client/server computing models like CORBA. A client would interact with an interface type as if it existed in their memory space, but they were really talking to a proxy that would handle all the messy details around marshalling request data into a request, communicating over the network to the remote object running on a server, and unmarshalling the response back to the client.
Spring uses this model for remoting. It also forms the basis for its aspect oriented programming model. Your code thinks it's dealing with a particular interface; Spring can weave in advice before, after, or around that instance and perform cross cutting operations like logging, transaction management, etc. on your behalf.
Some frameworks rely on a mechanism called instrumentation, which in short means to build a proxy of a given compiled bytecode, adding some code to it in some places we judge useful. This would implement many kinds of tasks, between them for example, adding a kind of profiling to a spring bean, as this library claims to do.
The Spring engine returns heavily instrumented proxies of every managed bean it offers - this way, you can use Spring declarative transaction handling, for instance. You would write "naive" daos without an actual connection handling, and "naive" service classes using the daos without an actual transaction handling - the instrumented proxies will include the boilerplate code with the connection instantiation, commits, rollbacks...
I hope this is of any help

How to stop Wicket creating multiple instances of Guice-injected singletons?

I'm a new Guice user, having been a long-time user of Spring IoC. I have a number of #Singleton classes for my service tier, which I understand is roughly equivalent to Spring's default bean scope.
However, when I am using #Inject in my Wicket pages a CGLib proxy of the target objects is created each time the page is constructed, thus creating new instances of my supposed-singletons.
Note that I'm injecting concrete classes, not interfaces.
How can I use #Inject and retrieve the single singleton instance of my Guice-injected objects?
Updated: Solution as per Sven's accepted answer
Inject interfaces in Wicket components rather than concrete classes. Despite much discussion on the subject in the linked thread, this appear to be the only practical solution.
The following issue gives some background:
https://issues.apache.org/jira/browse/WICKET-1130

Spring prototype scope - Use Cases?

I have clear understanding of the various scopes of Spring beans. But I am looking for some use cases of prototype scope of a bean in enterprise tier projects. It would be great if you can share some real life use cases of the prototype scope (not the request scope).
As someone who previously worked at SpringSource and have talked to the developers on this topic. Here is my take. Prototype is great for testing things out, hence the name prototype and not create new or something more description of creating a new instance of the bean each and every time you request it from the Spring container.
I have also found in my use over the years that I cannot think of any other place where prototype makes sense in any real-world production application. If your object holds state, it typically shouldn't be a Spring bean. I have found in all the applications I have worked on that all beans are Services, Repositories, and Singleton non state holding objects where I need to add features like Transactionality, JPA, JMS and the likes that give us the enterprise features that POJOs don't have.
The objects in my system that hold state are my Entities and View DTOs maybe, or other things that just make no sense to be a Spring Bean. So therefore in my applications in production there hasn't been a single "prototype" bean.
I used prototype beans to declare configured form elements (a textbox configured to validate names, e-mail addresses for example) and get "living" instances of them for every form being created in my webapp. The details are not important, only the principle, that I would summarize this way:
There is a class that has many config parameters
You need to create instances of it with a set of predefined configuration (fancy1, fancy2, stc.)
Think of the applicationContext.getBean("myBeanConfiguredFancy1") as a kind of factory method that creates the instance as preconfigured in the xml
I have used prototype mostly in conjunction with spring lookup-method. My application is a game server that needs to decode incoming bytes at tcp port. Consider the following bean definition
<bean id="channelBufferProtocol" class="org.menacheri.protocols.impl.ChannelBufferProtocol">
<lookup-method name="createLengthBasedFrameDecoder" bean="lengthFieldBasedFrameDecoder"/>
<property name="eventDecoder" ref="eventDecoder"></property>
<property name="lengthFieldPrepender" ref="lengthFieldPrepender"></property>
<property name="eventEncoder" ref="eventEncoder"></property>
</bean>
Inside the protocol implementation class, I have the following code to create the frame decoder pipeline.addLast("lengthDecoder", createLengthBasedFrameDecoder()); When this method is invoked, spring will create a new frame decoder instance and return it.
The bean returned by bean="lengthFieldBasedFrameDecoder" needs to be of scope prototype, since it is a stateful bean in my app.
Note: A protocol is nothing but a specific set of decoders and encoders chained together. "Chain of responsibility" design pattern.
We can use prototype scope in case of model classes(also called as Entities in hibernate) as application need different instances of model class for each thread/request.

Categories

Resources