Its been a while since I wrote the last blog, now I'm back and I will create a series of blogs about spring core and publish every week.
What is Spring Ioc Containers?
In the simplest way, I can explain spring-IoC Containers is that it is a program or we can say a component which we get from the spring framework just like we got Garbage collector with JVM.
Spring Ioc Container is the core component of the spring framework and it is responsible for creating an object, configure them, managing in the memory, injecting one object to another object, and also manages the complete lifecycle of objects.
So now you can understand that it maintain the lifecycle of an object from creation to the destruction.
For creating a bean we have to provide some information to the Spring Ioc Container which is XML configuration or the config file.
After that Spring Ioc Container automatically creates ready to use the object for the main application.
There are two types of Spring Ioc Container,
- Bean Factory
Bean factory is the basic implementation of the spring container and defined by the org.springframework.beans.factory.BeanFactory interface. The most commonly used BeanFactory implementation is the XmlBeanFactory class but it is not recommended to use in large applications.
2. Application Context
It is similar to the Bean factory but and inherits all the features of the Bean factory by extending it and also adds some more features such as the ability to resolve textual messages and i18 (internalization) and it is recommended over BeanFactory. It is an interface like a bean factory so we can not create an object, so there is three implementation class for the Application context.
a ) FileSystemXmlApplicationContext :
It configures the bean from the XML file and we have to give the full path of the XML configuration file.
b ) ClassPathXmlApplicationContext :
It searches for XML configuration by java classpath.
c ) WebXmlApplicationContext :
it searches for those beans in which we used Bean Annotation(@Bean).
How to create Bean?
It is very simple to create a bean, for this blog I will create a bean and inject the property by setter injection but in the next blog, I will show you all the various ways we can create beans.
Step 1: create a POJO class.
Step 2: Create a container in the main class.
In this step, we provide the implementation for the Application context by the ClassPathXmlApplicationContext class and give the XML config file as an argument to the container. By reading the metadata which is provided inside the XML file, Spring Ioc Container creates the beans and by the getBean() method we can get the object from the container.