Spring Dependency injection, singleton bean injection - spring

In Spring Dependency injection, if a prototype bean is injected in a singleton bean and after declaring the applicationcontext i am calling the getbean method for the singleton class object, then how many new instances are created for the prototype bean inside the singleton object?

Spring creates new instance of prototype bean every time it needed (for each #Autowired in application context). So in your case Spring creates only one instance of prototype (to inject it into a singleton bean).

Related

Spring bean instantiation

Does Spring instantiate the various beans in a non-blocking way? If I do a Thread.sleep in the afterPropertiesSet of a particular bean, does this block the instantiation of other beans?

Does an Object in Spring created every time we write getBean()?

I have read that whenever we do getBean() in spring, it returns desired object.
So does it mean, if i write call getBean() 1000 times, thousand object will be created ??
If yes, Than how Spring manages these objects ?
if No, Please explain how Spring works with respect to object creation ?
Is there something Object pool kind of concept ?
Please clarify my doubts. I am new to spring and is very confused whether spring framework is created to make our task easy or to make things more complicated.
Spring seems to be a web of XMLs :(
From the Spring Framework documentation on singleton bean factory scope:
The singleton scope
Only one shared instance of a singleton bean is managed, and all
requests for beans with an id or ids matching that bean definition
result in that one specific bean instance being returned by the Spring
container.
To put it another way, when you define a bean definition and it is
scoped as a singleton, the Spring IoC container creates exactly one
instance of the object defined by that bean definition. This single
instance is stored in a cache of such singleton beans, and all
subsequent requests and references for that named bean return the
cached object.
To sum it up, no, Spring will create only a single instance of each bean in a bean factory unless you change the default scope of singleton to some other bean scope.
Other bean scopes include:
Bean scopes
singleton (Default) Scopes a single bean definition to a
single object instance per Spring IoC
container.
prototype Scopes a single bean
definition to any number of object instances.
request Scopes a single bean definition to the
lifecycle of a single HTTP request; that is, each HTTP request has its
own instance of a bean created off the back of a single bean
definition. Only valid in the context of a web-aware Spring
ApplicationContext.
session Scopes a single
bean definition to the lifecycle of an HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the
lifecycle of a global HTTP Session. Typically only valid when used in a portlet
context. Only valid in the context of a web-aware Spring
ApplicationContext.

Java Spring bean scopes: singleton vs application

Could anyone explain the difference between these two Spring bean scopes?
I'm familiar with the Singleton pattern.
Would this be the only difference?
You can have a list of beans in the Spring container using application scope.
Also, are you able to run multiple web servers in one Spring container? If yes, that would be a reason to use the application scope over the singleton scope since otherwise the bean would get shared over the two servers.
The documentation explains it:
This is somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring 'ApplicationContext' (or which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute
In application scope, the container creates one instance per web application runtime.
The application scope is almost similar to singleton scope. So, the difference is
Application scoped bean is singleton per ServletContext however singleton scoped bean is singleton per ApplicationContext. It means that there can be multiple application contexts for single application.
SINGLETON SCOPED BEAN
//load the spring configuration file
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("context.xml");
// retrieve bean from spring container
MyBean myBean = context.getBean("myBean", MyBean.class);
MyBean myBean2 = context.getBean("myBean", MyBean.class);
// myBean == myBean2 - output is true.

Does the test class create implementations to inject in spring dependency injection

In this example on spring dependency injection here
Whne the final test class is run, after this line:
MySpringBeanWithDependency test = (MySpringBeanWithDependency) factory
.getBean("mySpringBeanWithDependency");
Which implementation of writer class will get injected? The test class still is responsbile for creating an actual implementation and injecting it before calling business methods on the Writer. Is it true?
In both the annotation-based example and the XML-based example, Spring will inject the NiceWriter bean into the MySpringBeanWithDependency bean.
For the annotation example, this is because the NiceWriter class is annotated with #Service (while the Writer class is not) and Spring will discover this via classpath scanning and autowire it into MySpringBeanWithDependency.
For the XML example, this is because the NiceWriter class is used to define the bean with id writer, which is referenced as the "writer" property of the bean with id mySpringBeanWithDependency.
In both cases, the MySpringBeanWithDependency bean is instantiated with dependencies injected via Spring, and is thus ready to use. It is not responsible for managing its IWriter dependency. This is why dependency injection (DI for short) usually goes hand-in-hand with inversion-of-control (IoC for short). Spring provides an IoC container that uses DI.

Spring setter dependency injection after all beans have been created

I have a set of Spring beans created using constructor injection. Since there are (by design) circular references to other beans, I'd like to post-process the beans once they are all created to inject the references to other beans.
Initial attempts at using BeanPostProcessor show that the BeanPostProcessor is running after EACH bean is instantiated, not waiting until all have been instantiated.
Does Spring provide a mechanism for post-processing as set of beans after all have been created?
If you're creating the beans in an ApplicationContext, the ApplicationContext fires ApplicationEvents to any registered ApplicationListener callbacks. One of those should tell you when all the beans in the context are wired together via Spring.
Here's what the documentation says about circular dependencies:
If you use predominantly constructor injection, it is possible to
create an unresolvable circular dependency scenario.
For example: Class A requires an instance of class B through
constructor injection, and class B requires an instance of class A
through constructor injection. If you configure beans for classes A
and B to be injected into each other, the Spring IoC container detects
this circular reference at runtime, and throws a
BeanCurrentlyInCreationException.
One possible solution is to edit the source code of some classes to be
configured by setters rather than constructors. Alternatively, avoid
constructor injection and use setter injection only. In other words,
although it is not recommended, you can configure circular
dependencies with setter injection.
Unlike the typical case (with no circular dependencies), a circular
dependency between bean A and bean B forces one of the beans to be
injected into the other prior to being fully initialized itself (a
classic chicken/egg scenario).
I would just use setter injection in this case, or try to avoid the circular dependency in the first place. Another solution is to make one of the beans BeanFactoryAware, and to lookup the other bean from the bean factory when the reference is needed.

Resources