How does IoC create instances for beans - spring

I learned that when IoC container initializes, it creates instances and injects the dependencies.
How does it create the objects? Is it creating them using the new operator?

In Java the only way to instanciate an object, is to call a constructor.
You can call the constructor using the new operator or by reflection.
Spring use reflection to instanciate an object.

1 Classes if they have a non-private constructor defined and same is declared in configuration metadata, are instantiated using reflection. getDeclaredConstructor() of a class API
Some classes are instantiated using the static or non static factory methods if defined in the metadata.
Please read section 4.3.2 Instantiating beans from spring documentation

Related

Why does Spring allow beans with Private constructors to be instantiated?

As mentioned in the answers to this question, Spring can invoke private constructors through reflection.
Generally when we create a class with a private constructor, we use it for preventing instantiation outside of the class as in the case of a Singleton class, or for preventing instantiation of classes with static utility methods/constants.
What is the reason why Spring allows beans with private constructors to be instantiated ?
You would have to ask the Spring developers. It's probably a matter of convenience.
It allows you to create Classes that cannot be instantiated except through the Spring Container, or other reflection based technique.
It allows you to require your Java code to use other constructors which require different inputs.
If Spring could not use a private or package access constructor then you would have to declare constructors with public access. Your Java code could then use them. Your intent not to use classes this way would not be so clear.

Spring-Boot: share an object between components

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.

Inject properties into object which is not a spring managed bean

I have a spring application where in some cases I need to create an object at runtime, as opposed to a spring injected bean. This object should be created with properties that come from the application context however. If this object is not spring-injected, how can I still take advantage of IoC? Should I make these object properties static and inject them into a bean via non-static setters?
You can still inject properties for object which is not created by spring.
To do that you should use #Configurable annotation. And you should enable LoadTimeWeaving or CompileTimeWeaving. But I think that can be overkill for your situation.

Getting Spring object instantiation right

I'm new to Spring and a little confused about how it works. I get that I can use the application context to instantiate beans and have them populated. However, is the idea that I should be able to just write Bean b = new Bean() and then have Spring to somehow automagically populate that Bean?
I'm experimenting with Spring in a web application, and as far as I can see I need to inject the ApplicationContext into, say, the servlets to be able to instantiate other beans (services, daos etc.) from there. It's a bit cumbersome, but probably works.
However, is Spring meant to be able to hook into any object instantiation which happens on classes defined as beans in applicationContext.xml?
Spring is an Inversion of Control container. A bean is an object whose life cycle is managed by Spring. If you want Spring to populate an object, it needs to go through Spring, ie. it needs to be bean.
is Spring meant to be able to hook into any object instantiation
which happens on classes defined as beans in applicationContext.xml?
Spring doesn't hook into anything. You configure your beans and the relationships between them with Spring and Spring handles creating the instances and linking them up.
For domain objects, Spring provides a solution via the #Configurable annotation: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-atconfigurable
It requires compile- or load-time-weaving and, thus, introduces some additional complexity but having the convenience of using the standard new Bean() syntax plus Spring's autowiring is worth it in my opinion.
Alternatively, you could define your domain objects as beans with prototype scope and use some factory to create them using the Spring ApplicationContext.getBean() method. With a scope of prototype a new instance will be returned every time and since you go through the ApplicationContext, Spring will do all the dependency injection magic as usual.
As for services and other beans with singleton scope, you would typically NOT retrieve them by first injecting the ApplicationContext and using it but instead you would inject them via either a constructor, setter or annotation-based strategy. The documentation covers that in detail: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-collaborators

Spring InitializingBean interface

In XML file in spring we have two bean with different id but same class. They have the same properties offcourse. Now I have InitializingBean interface and in afterPropertySet() I am just printing the value of properties.
Its printing the values two times for me?
According Spring Documentation:
afterPropertySet()
Invoked by a BeanFactory after it has set all bean properties supplied (and satisfied BeanFactoryAware and ApplicationContextAware).
So the short answer on your question is: yes
Spring doesn't manipulate classes or object. Spring manipulates Bean Entity. It is the simplest object manipulated by Spring IOC. Bean has additional behaivior rules introduced by Spring.
If you create two beans for example with Singleton scope and not Lazy initializated Spring creates two instances of your class.
Probably you are calling this Class also invoking a Test or by launching a Integration test like this . check the breakpoints , if you are using SpringRunner, try to mock the component

Resources