Removing Spring scoped beans proxy overhead - spring

How can I customize existing bean injection mechanism so that scoped bean calls method of another bean without additional proxy provided they have the same scope?
I have many nested and performance sensitive loops that call singleton beans and resolve scope of their common data using thread local storage. I'd like to re-factor those singleton scope beans so that instance fields can be safely used.
I will have to change how dependency injection works for those beans. For example, eagerly initialize and set all the references scoped beans when a new scoped bean is created. This should be do-able with a post processor but I need to prevent default wiring from happening in those cases and also retain non-scope related proxies. I have impression that it is going against fundamental Spring design choices and I'm curious whether this idea was intentionally left out.

Related

Real use case of proptotype scope of spring beans

Waht is a real example for such kind of stuff? I have already looked through this post, but the answers to this post seem inconclusive to me. Also there is an advice: "As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans" - from spring reference, but why do we need our services to be stateful? We can just share this state as a simple dto among services' calls.
One popular use of it is to associate separate instance of a bean to each HTTP session.
Consider your have a bean class called UserConfig. You can set this bean with prototype scope, and configure such that each new HTTP session has its own UserConfig bean instance. (Spring MVC has its own scope called "session" for this purpose, but the concept is similar)
Also the user can change your site configuration, and the changed state is saved on its own instance of the bean (as opposed of altering the global single instance if you set it into singleton scope)

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.

Can the object created in IoC container be called Singleton. If not - why?

can the object created in IOC container can be called Singleton if yes why if no why?
Can anybody explain me in detail in simple words how IOC conatiner exactly manages the objects..
You can say that a spring singleton is not a singleton.
Singleton has its meaningful scope, the spring singleton scope is the spring ioc container. And the classic singleton's meaningful scope is the ClassLoader. You may find more about the distinction between these kinds of singleton here: A spring singleton is not a singleton.
Spring manage its singleton in a hashmap(Singleton Cache). When you get a bean from the spring ioc container, it first checks if the bean has already exists in the singleton cache, if does, it returns the bean from the singleton cache
Spring (and other ioc-containers) offer different scopes. One of the scopes is singleton - i.e. the container instantiates the object only once and gives / injects only one instance. Singleton is the default scope, so most of the beans are indeed singletons from the point of view of the container- i.e. they have only one instance in it.
However, there are other scopes, like prototype or the web-based request and session.
In managing the bean, the container does the following:
invokes the #PostConstruct and #PreDestroy methods (or the init and destroy methods, configured by any available means)
injects all their defined dependencies (=sets other beans existing in the container to the fields of this bean)
creates AOP aspects around the bean methods
Note: you can instantiate more than one objects of a class that is defined as as singleton bean. The container instantiates the object only once, but your code is not limited to instantiating it multiple times.
can the object created in IOC
container can be called Singleton if
yes why if no why?
Read this, from the Spring Reference.
Can anybody explain me in detail in
simple words how IOC conatiner exactly
manages the objects..
Read this, from the Spring Reference.
I use a more generic definition of a Singleton:
A Singleton is an object that is
guaranteed to be unique inside a given
scope.
This scope is the ClassLoader in the traditional singleton definition, but other possible scopes are:
Application (may be clustered and therefor classic Singleton won't help)
HTTP Session
Thread (implemented through ThreadLocals)
HTTP Request etc.
(I really like the Seam method Component.getInstance(Class, ScopeType) that lets you choose the Scope you want a singleton for.)
You might find this Google Groups thread useful.

Does IOC container makes object's when project is deployed?

How IOC container helps maintaing objects by creating once and injecting when required???
Read the spring reference about Bean Scopes and about Lazy Initialization:
By default, ApplicationContext
implementations eagerly create and
configure all singleton beans as part
of the initialization process.
Generally, this pre-instantiation is
desirable, because errors in the
configuration or surrounding
environment are discovered
immediately, as opposed to hours or
even days later. When this behavior is
not desirable, you can prevent
pre-instantiation of a singleton bean
by marking the bean definition as
lazy-initialized. A lazy-initialized
bean tells the IoC container to create
a bean instance when it is first
requested, rather than at startup.
In XML, this behavior is controlled by
the lazy-init attribute on the
element; for example:
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>
It depends how you have configured the specific dependency, you can have singleton, per request, http etc lifecycles

Resources