Configuring a Bean in Spring / Spring Boot

In Spring and Spring Boot, beans represent objects that are managed by the Spring container and are responsible for providing services, such as data access, business logic, or infrastructure functionality. In this article, we’ll explore various ways to configure beans in Spring and Spring Boot.

1. Configuring Beans in Spring / Spring Boot

There are multiple ways to configure beans in Spring and Spring Boot:

  • Annotation-based Configuration: Annotations such as @Component, @Service, @Repository, and @Controller are used to mark classes as Spring-managed beans. These annotations can be used to automatically detect and register beans in the Spring application context.
  • Java Configuration: Spring provides @Configuration and @Bean annotations to define beans using Java configuration classes.
    • @Configuration marks a class as a configuration class.
    • @Bean is used to define individual beans.
  • XML Configuration (Spring XML Schema): Beans can be defined in XML configuration files using the <bean> element. While XML configuration is less common in modern Spring applications, it is still supported for legacy and specific use cases.

Let’s explore each method in detail:

2. Annotation-based Configuration [for Stereotype Annotations]

Annotation-based configuration is the most common approach used in modern Spring applications. When Spring loads, Java beans are scanned in the following places:

@Configuration
@ComponentScan(basePackages = "com.howtodoinjava.spring")
public class AppConfig {
}

When component scanning is enabled, we can define the beans using one of the following annotations as appropriate.

  • @Component
  • @Repository
  • @Service
  • @Controller
  • @RestController
package com.howtodoinjava.spring.service;

@Service
public class EmployeeManager {
 

  public Employee create(Employee employee) {
    //...
  }
}

Now we can load the beans in context using AnnotationConfigApplicationContext as follows:

//Method 1
//ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
 
//Method 2
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
 
EmployeeManager empManager = ctx.getBean(EmployeeManager.class);
Employee emp = empManager.create();

3. Java Configuration [for @Bean Annotation]

Instead of annotating the classes with Spring annotations, we can declare them as Spring bean in the configuration class:

@Configuration
public class AppConfig {
   
    @Bean
    public EmployeeManager employeeManager() {
        return new EmployeeManager();
    }
}

Now we can load this bean into the application context as follows:

//Method 1
//ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

//Method 2
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
 
EmployeeManager empManager = ctx.getBean(EmployeeManager.class);
Employee emp = empManager.create();

4. XML Configuration

XML configuration involves defining beans in XML files using the <bean> element. While less common than annotation-based and Java configuration, XML configuration is still supported in Spring.

4.1. Bean Definitions

When using XML files, we can define the beans either in a single file or we can distribute the beans in separate files for better code structure. Either way, the bean definitions will be created the same.

<?xml version="1.0" encoding="UTF-8"?>
<beans>

  <bean id="operations" class="com.howtodoinjava.core.demo.beans.Operations"></bean>
  <bean id="employee" class="com.howtodoinjava.core.demo.beans.Employee"></bean>
  <bean id="department" class="com.howtodoinjava.core.demo.beans.Department"></bean>

</beans>

If we have created multiple bean definition files, we can import the files in the current file as follows:

<beans>
   
  <import resource="employee.xml"/>
  <import resource="department.xml"/>
   
  <bean id="operations" class="com.howtodoinjava.spring.beans.Operations"></bean>
   
</beans> 

4.2. Loading Beans into Context

To load the bean definitions files and thus initialize beans, we can pass the bean definition file name into the constructor of any one of the ApplicationContext implementations.

  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext
  • XmlWebApplicationContext

Following is an example of loading the beans.xml file into ClassPathXmlApplicationContext. Note that the bean definition file is located at '/src/main/resources/beans.xml'.

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:beans.xml");

Employee employee = ctx.getBean(Employee.class);
Department department = ctx.getBean(Department.class);
Operations operations = ctx.getBean(Operations.class);

Program output:

Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]

Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [employee.xml]

Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [department.xml]

5. When to Use Each Method

  • Annotation-based Configuration: Use this approach for most cases in modern Spring / Spring Boot applications. It’s concise, easy to read, and promotes convention over configuration.
  • Java Configuration: Use Java configuration when you need more control over bean creation, or when you want to use features like conditional bean registration.
  • XML Configuration: Use XML configuration for legacy applications or when working with frameworks that require XML configuration.

6. Conclusion

Configuring beans in Spring and Spring Boot is a fundamental aspect of application development. Understanding the different ways to configure beans and when to use each method is essential for building maintainable and scalable applications.

Whether you prefer annotation-based configuration, Java configuration, or XML configuration, Spring provides flexible options to suit your needs. Choose the approach that best fits your project requirements and development style.

Happy Learning !!

Source code on github

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode