Spring Beans in Java

Reading Time: 2 minutes

Spring IoC container is the core of the Spring Framework.
In spring-based applications, objects live inside a spring container
The container instantiate the objects, wires them together and manages their complete life cycle from creation till destruction.These objects in the Spring IoC container are referred to as beans.

What is Inversion Of Control(IoC)?

IoC simply means giving control to spring container to create and instantiate the spring beans

Let`s say you want to create a new object, what you would do is “new NewObject” inside the code, which creates a rigidly coupled application.

IoC allows the spring container to the handle the lifecycle of the object,which help in de-coupling.

IoC scans the annotations to the find the objects using @ComponentScan In case of annotations we can define beans as @Services @Controller @Repository @Component on top of the class definition.

To manage the objects spring needs to own that object, know where the object is and where it is. It finds the objects within the class and turns them into a Singleton Bean. After that process, the instantiation of those of object, their life cycle and destruction are managed by a Spring IoC container.

@Component or @Bean

When should you use @Component?

It is applied on class level. When we annotate a class with @Component, no need for us to manually use the new keyword. It is handled automatically by Spring.

When should you use @Bean?

When you want to wire components from 3rd-party libraries you can`t have access to the source code so it is not feasible to annotate its classes with @Component.

The @Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.

Look at this example.

Annotate the config class with @Configuration
This will expose this ServiceFactory instance as a Bean in your spring application that you can simply autowire.
If you want you can create BeanA and BeanB as Beans as well and then reference them in your creation of the ServiceFactory

@Configuration
class SomeConfigurationClass {
    @Bean
    public ServiceFactory serviceFactory() {
        return new ServiceFactory(beanA(), beanB()):
    }
    @Bean
    public ServiceA beanA() {
        return new BeanA();
    }
    @Bean
    public BeanB beanB() {
        return new BeanB();
    }
}

Stay tuned for next blog on dependency injection in spring!

References:

https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s02.html
https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s11.html
https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

Knoldus-blog-footer-image