Spring-Boot: share an object between components - spring

I have a custom object which I like to share between different Spring-Boot components (e.g. WebHandler, Authenticator, Filter).
Maybe the easiest way is a static object in the main-class but thats not very elegant.
Whats the most common way to do it?

The whole point of spring as a container is to manage your objects.
Now statics do not have a well defined lifecycle ( when exactly this object gets created, who disposes it when the application gets closed, etc)
Speing answers all these questions by using thecdependency injection techniques. If you're already using spring then you should define this 'shared object' as a spring bean (by default it will have scope singleton just like static object that you've proposed but managed by spring container which is better - it will manage the lifecycle of the object by itself)
Then given the classes that must be dependent of the object are beans by themselves you can inject that bean:
class MySharedObject {}
class MyWebHandler implementsWebHandler {
private final MySharedObject mySharedObject;
public MyWebHandler(MySharedObject mySharedObject) {
this.mySharedObject = mySharedObject;
In addition to the lifecycle management this way allows easy unit testing of classes that use the shared object (like 'MyWebHandler' in this case) - now uou can create a stub/mock of the shared object and pass it into the handler - something that cannot really be easily done when using statics
So in summary if you can use spring and define it as a bean - by all means do so, the usage of statics is discouraged if you already have a dependency injection container

If you have shared object first of all it should not contain any state as differents components can change it and also it should be thread safe.
It is fine to reuse it across all components via #Autowired annotation but you need to be sure that it is threadsafe. Spring bean scope singleton is not thread safe out of box it dependes how you write the code.
You can use as static method but it dependes on logic which you have and if those component has an dependency on another objects and if they need to in spring IOC.

Related

Which is better to implement a singleton in a Spring application: a bean or a static field?

I am developing Spring MVC app, i need to implement singleton pattern for some kind of utilities, ex: imageuploader and others.
My question is: in what way to implement singleton for this utilities, to initialize beans for these classes and inject where i need like Controllers, Services, DAO?, or to use static field implementation of singleton to keep instance of this class?
First, try to avoid singleton as it's considered to be a bad practice. Also their interactions with other instances are difficult to test and validate, compared to non-singleton instances.
If you absolutely need it, I'd suggest you use a Spring bean so you can exploit the autowiring mechanism and Spring's bean lifecycle.
See the Beans section of the Spring reference doc for more info.
Using a Spring bean as will allow you to easily inject a mock in unit tests. However, you will only be able to access it from other Spring beans (or objects created by Spring beans that pass in a reference to it).
Also see this discussion in this question: Difference between static class and singleton pattern?
Traditionally, you'd use PropertyPlaceholderConfigurer to inject config from properties files into a Spring web-app. This blog discusses a variety of newer ways to do this with Spring.

Use/Purpose of beans in Spring

Could someone give an overview or a summary of what the purpose of beans in a Spring framework context?
I understand the standard Java bean (no arg constructor, getters/setters, often serialized), but the Spring bean purpose seems to be different.
Is it a way of implementing the Singleton design pattern (one instance, for like factory classes) in a simple, reusable fashion?
I've mainly used Spring with annotations, but I feel I need to grasp this in order to understand Spring.
Thanks!
Beans are objects that form the backbone of the application.
A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container; other than that, there is nothing special about a bean.It is in all other respects one of probably many objects in your application.
Spring beans are defined in a spring configuration file or by using annotations, instantiated by the Spring container, and then injected into your application.
Spring beans will not be singleton design pattern until you explicitly make them to be.The singleton design pattern and the spring scope 'singleton' are different things.You can define different bean scopes depending on your requirements.
The scopes could be :
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP
session.
The default scope is singleton.
I understand the standard Java bean (no arg constructor,
getters/setters, often serialized), but the Spring bean purpose seems
to be different.
You mean always serialized. Why do you think the purpose seems different?
In the end, you write classes. A lot of time these are POJOs, Plain Old Java Objects. Sometimes you implement an interface or extend a class, but its all just classes.
Beans are just classes. Don't overcomplicate it.
Now Spring might take your beans (classes) and manage them for you via any of a number of policies (prototype, singleton) but that doesn't change what a bean is, it speaks to how Spring manages the bean.
To understand best, you should get familiar with dependency injection. In a few words dependency injection allows you to use objects, or services without explicitly creating them (of course, it gives other benefits, but let's focus on the question). This is achieved by maintaining a dependency container that is - roughly said - a collection of beans.
A bean is a service/component you use in your application. Unlike the EJB, with Spring the bean is not constrained to constructor arguments or specific annotations (especially if you use xml contexts). You register a bean with a container (by defining a context), and when you require it, the container will provide you with an instance of that bean. In order to create the bean, the container examines its class and constructors, and uses any other registered beans within that context, to call the appropriate constructor or property setter.
You can configure a bean to be a singleton - this is not a singleton as in the design pattern term. Singleton beans are created once within the container, and the same instance is used whenever the bean is requested from that container. You can also use the prototype scope to force the container to create a new instance each time.

What is the prototype Spring Bean used for?

By default, the Bean created by Spring is singleton. They are thread-safe because they are stateless. When we want Spring to create a stateful Bean, we need to use prototype scope for the Bean definition. We need to take care of the thread-safe issues for them. All stateless Bean will be polluted when they are injected by the prototype bean. So, I just can not image where we can use the prototype scope. Can you give some typical scenario that we can / need to use prototype Spring Bean? Also how can we void the stateful pollution on other singleton beans?
There are many reasons to use prototype scope, e.g., any time you'd use "new" instead of using a singleton. A per-user bean, a per-request bean, a collection of unique beans, etc. After all, in any non-trivial application, don't you use non-singletons far more than singletons?
Singleton-scoped beans aren't thread-safe simply because they're singletons–they must be written to be thread-safe. They don't become thread-safe magically. A bean's scope is just that, its scope: it doesn't make the bean appropriate for the particular scope–that's up to the developer.
I perceive prototype scoped beans as an alternative to factory classes used to create objects. The difference is in case of prototype beans spring will save you some code for dependency injection and will also automatically proxy your objects for transactions etc. when appropriate.
I myself prefer the factory approach. One reasonable scenario for prototype scope I encountered was a stateful object, needed by different known beans and each required its own copy. A dedicated factory class would be redundant in this scenario since I did not need to create objects on the fly but only during other beans' instantiation.

Spring injection and object instantiation

I am trying to better understand Spring instantiation of beans. To illustrate my doubts, let's assume we have a Service class being wired in a Controller, here are the questions:
How will Spring manage the lifecycle
of the Controller? Will a new object
be created per request?
Once a Service is instantiaded and
wired to a Controller, will Spring
re-use that object reference to wire
it in to other beans?
Like Servlets, Controllers' lifecycle spans beyond requests. All of controllers in the application are instantiated only once when application is started; afterwards those objects are re-used to service all requests.
As Bozho pointed out, by default all beans are in singleton scope, therefore they will be re-used everywhere, unless specified otherwise.
The default scope is singleton, which means beans will be re-used (i.e. 1) no, a new object will not be created per request, and 2) yes, the object reference will be reused).
This can all be configured. Have a look at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes.
It all depends on the bean scope. By default all beans are in singleton scope - that is, they are instantiated by the container only once.
If you specify #Scope("request") (or the xml equivalent) then the same service object (singleton) will be injected in all instances of the request-scoped controller. (But you rarely need request-scoped controllers)

Plain old singleton or spring singleton bean?

I have a service in my application which is a singleton.
My application is being bloated with the use of spring framework.
I am confused over to use the singleton service as
1: Plain Old Singleton [Access them statically when required]
OR as a
2: Spring singleton bean. [Use DI to inject when required]
Which approach is correct ?
The Spring singleton scope is not the same as the Singleton design pattern, which is not the same as a class with static methods.
From the documentation
"Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. 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."
Also, note you need to be very careful using a Spring singleton as a service that web requests will utilize. Since each request is on its own thread, you can have threading issues if your singleton maintains any state.
To answer your question: Create a class that implements an interface, and use Spring to DI it appropriately. If your service does not maintain state, you can scope it to singleton, otherwise you can scope it to prototype.
I use Spring's beans whenever possible. The framework was designed to manage these things, and it is probably better than me at it. Another reason to use Spring's dependency injection is the possibility to unit-test with mocks instead of the real utility code, thus focusing the unit-test to the exact scope.
EDIT:
To answer the question in the comment, the only case I can think of for a non-bean singleton would be a utility code class, which would contain short pieces of generally reusable code in public static methods. Anything else requires instantiation, and therefore - a bean.

Resources