Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java singleton class vs JSF application scoped managed bean - differences?

Is there a difference using a singleton class and an application scoped managed bean to hold application data?

I need to lookup certain JNDI ressources such as remote bean interfaces and therefore I wrote myself a singleton to cache my references and only allow single references. (ServiceLocator)

I opened my website in two different browsers and that singleton got only initialized once. So I assume its application scope?

Any other benefits of a application scope managed bean then being able to access its properties in jsf?

like image 866
djmj Avatar asked Mar 10 '12 23:03

djmj


People also ask

What is an application scoped bean?

When beans are application scoped, the same instance of the bean is shared across multiple servlet-based applications running in the same ServletContext, while singleton scoped beans are scoped to a single application context only.

Is bean a singleton?

By default, the scope of a bean is a singleton.

What is @ApplicationScope?

Annotation Type ApplicationScope @ApplicationScope is a specialization of @Scope for a component whose lifecycle is bound to the current web application. Specifically, @ApplicationScope is a composed annotation that acts as a shortcut for @Scope("application") with the default proxyMode() set to TARGET_CLASS .

What is singleton bean scope in Spring?

The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition.


1 Answers

Singletons are not unit testable nor abstractable nor extendable. Singletons are also unnecessarily complex to reliably create and maintain if your sole purpose is to have application scoped data (at least, if you really want a fullworthy singleton for it for some reason -most starters don't even exactly understand what a singleton is supposed to be).

"Just create one" like an application scoped managed bean is much simpler to develop, test and maintain. JSF as framework will guarantee that only one instance will be created and reused during web application's lifetime.

See also:

  • Singleton vs Just Create one
  • How to choose the right bean scope?
like image 144
BalusC Avatar answered Sep 27 '22 19:09

BalusC