Spring Bean

Spring Bean is one of the major concepts in the spring framework. To work with the spring framework, it is essential to know about spring beans. In this post, we try to give clear answers not vague.

Spring Bean is another kind of java object. An object-oriented language or framework have objects/bean which holds state and behaviour defined in class methods.

In the spring framework, we have beans that are created and maintained in a spring container. Using a spring container, we get loose coupling in the application. so, there is no headache for the creation of Java objects instead we get spring beans (objects) from the spring IOC container.

As per Spring Framework:
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

Container Overview:

Spring container is represented by the ApplicationContext interface and BeanFactory interface. ApplicationContext extends the BeanFactory interface. They are responsible for instantiating, configuring and assembling the beans.

The container gets all the information on “How” objects should be instantiated, assembled and configured through configuration metadata i.e. XML, annotations, and Java config. XML is the oldest way, nowadays prefer to use annotation and Java config.

Dependency Injection:

Every other bean (object) can depend on other beans (objects) to perform the functionality. So, we can call it dependencies and we need to inject these dependencies in our main class who actually performs the functionality. To build the bean, we must require their dependent beans otherwise we get an exception from the framework. In the below example, the user bean is created in the spring IOC container and also provide the dependent bean information to the container that is Address class.

@Component
class User {
    @Autowired
    private Address address;
}

Spring Bean creation:

Implicit: @Component and its specialized versions like @RestController, @Service, and @Repository and also the default scoped type is singleton. Using these annotations we can create spring beans. Spring internally manage the bean creation process using @Component but we can customize the process using @Bean. Check the below example:

@Component
class Address {
    private String housNumber;
    private String street;
    // .... more code....
}

Explicit: @Bean, using this annotation we can customize the bean creation in spring.

Leave a Reply

Your email address will not be published. Required fields are marked *