Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

How to Create a Spring Bean in 3 Different Ways?

In the Spring framework, a bean is an object that is instantiated, configured, and managed by the Spring IoC (Inversion of Control) container. Spring beans are defined in the Spring container and can be injected into other beans or classes.

Here are three primary ways to define and create a Spring bean:

1. Using XML Configuration:

This is the traditional way to define Spring beans. You'll need an applicationContext.xml or any XML configuration file.

Step 1: Create your Java class.

public class HelloWorld {
    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println("Your Message: " + message);
    }
}

Step 2: Define your bean in the XML configuration file.

<bean id="helloWorld" class="com.example.HelloWorld">
   <property name="message" value="Hello World!"></property>
</bean>

Step 3: Get the bean from the Spring context.

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();

2. Using Java-based Configuration:

Instead of XML, you can configure the Spring container using Java.

Step 1: Create a configuration class with @Configuration annotation.

@Configuration
public class AppConfig {
    @Bean
    public HelloWorld helloWorld() {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.setMessage("Hello World from Java Config!");
        return helloWorld;
    }
}

Step 2: Get the bean from the Java-based Spring context.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = context.getBean(HelloWorld.class);
obj.getMessage();

3. Using Component Scan:

Spring can automatically detect beans if you annotate them and configure component scanning.

Step 1: Annotate the class with @Component (or @Service, @Repository, @Controller, etc. depending on the type).

@Component
public class HelloWorld {
    // ... same as above
}

Step 2: Enable component scanning in XML or Java config.

For XML:

<context:component-scan base-package="com.example" />

For Java:

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

Step 3: Get the bean from the Spring context.

Depending on whether you used XML or Java config for the component scan, get the bean accordingly, as demonstrated in the prior methods.

While all three methods are valid, the industry trend has been moving away from XML-based configuration in favor of Java-based configuration or component scanning, as they offer type safety and are often considered more intuitive and cleaner.

  1. Creating Spring beans using XML configuration example:

    • Description: Define Spring beans in an XML configuration file.
    • XML Code:
      <!-- beans.xml -->
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans.xsd">
      
          <bean id="myBean" class="com.example.MyBean"/>
      </beans>
      
    • Java Code:
      public class MyBean {
          // Bean implementation
      }
      
  2. Annotation-based approach for defining Spring beans:

    • Description: Use annotations to define Spring beans.
    • Java Code:
      @Component
      public class MyBean {
          // Bean implementation
      }
      
  3. Using @Component annotation to define Spring beans:

    • Description: Annotate classes with @Component to automatically register them as Spring beans.
    • Java Code:
      @Component
      public class MyBean {
          // Bean implementation
      }
      
  4. Configuring Spring beans with @Bean annotation in Java:

    • Description: Use the @Bean annotation in a configuration class to define beans.
    • Java Code:
      @Configuration
      public class AppConfig {
      
          @Bean
          public MyBean myBean() {
              return new MyBean();
          }
      }
      
  5. Mixing XML and annotation-based bean creation in Spring:

    • Description: Combine XML and annotation-based configuration for Spring beans.
    • XML Code (beans.xml):
      <bean id="xmlBean" class="com.example.XmlBean"/>
      
    • Java Code:
      @Component
      public class AnnotationBean {
          // Bean implementation
      }
      
  6. Defining singleton and prototype beans in Spring XML:

    • Description: Configure beans as singleton or prototype in XML.
    • XML Code:
      <bean id="singletonBean" class="com.example.SingletonBean" scope="singleton"/>
      <bean id="prototypeBean" class="com.example.PrototypeBean" scope="prototype"/>
      
    • Java Code:
      public class SingletonBean {
          // Singleton bean implementation
      }
      
      public class PrototypeBean {
          // Prototype bean implementation
      
  7. Creating Spring beans with constructor injection in XML:

    • Description: Inject dependencies using constructor injection in XML configuration.
    • XML Code:
      <bean id="dependencyBean" class="com.example.DependencyBean"/>
      <bean id="constructorBean" class="com.example.ConstructorBean">
          <constructor-arg ref="dependencyBean"/>
      </bean>
      
    • Java Code:
      public class DependencyBean {
          // Dependency bean implementation
      }
      
      public class ConstructorBean {
          public ConstructorBean(DependencyBean dependency) {
              // Constructor injection
          }
      
  8. Managing dependencies in Spring beans using annotations:

    • Description: Use @Autowired and other annotations for dependency injection.
    • Java Code:
      @Component
      public class MyBean {
      
          @Autowired
          private DependencyBean dependency;
      
          // Bean implementation
      }
      
  9. Configuring property values for Spring beans in XML:

    • Description: Set property values for beans in XML configuration.
    • XML Code:
      <bean id="propertyBean" class="com.example.PropertyBean">
          <property name="propertyName" value="propertyValue"/>
      </bean>
      
    • Java Code:
      public class PropertyBean {
          private String propertyName;
      
          // Setter for propertyName
      }
      
  10. Implementing custom initialization and destruction methods for Spring beans:

    • Description: Define custom methods for bean initialization and destruction.
    • Java Code:
      @Component
      public class MyBean {
      
          @PostConstruct
          public void customInit() {
              // Custom initialization logic
          }
      
          @PreDestroy
          public void customDestroy() {
              // Custom destruction logic
          }
      }
      
  11. Using Java configuration to create Spring beans with dependencies:

    • Description: Define beans with dependencies using Java configuration.
    • Java Code:
      @Configuration
      public class AppConfig {
      
          @Bean
          public DependencyBean dependencyBean() {
              return new DependencyBean();
          }
      
          @Bean
          public MyBean myBean(DependencyBean dependencyBean) {
              return new MyBean(dependencyBean);
          }
      }
      
  12. Conditional bean creation in Spring with annotations:

    • Description: Conditionally create beans based on certain conditions.
    • Java Code:
      @Component
      @ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
      public class ConditionalBean {
          // Bean implementation
      }
      
  13. Configuring lazy initialization for Spring beans in XML:

    • Description: Configure beans for lazy initialization in XML.
    • XML Code:
      <bean id="lazyBean" class="com.example.LazyBean" lazy-init="true"/>
      
    • Java Code:
      public class LazyBean {
          // Bean implementation
      }
      
  14. Dynamic bean creation with factory methods in Java configuration:

    • Description: Use factory methods to dynamically create beans.
    • Java Code:
      @Configuration
      public class AppConfig {
      
          @Bean
          public MyBeanFactory myBeanFactory() {
              return new MyBeanFactory();
          }
      
          @Bean
          public MyBean myBean() {
              return myBeanFactory().createMyBean();
          }
      }
      
  15. Defining aliases for Spring beans in XML configuration:

    • Description: Define aliases for beans to provide alternative names.
    • XML Code:
      <bean id="originalBean" class="com.example.OriginalBean"/>
      <alias name="aliasBean" alias="originalBean"/>
      
    • Java Code:
      public class OriginalBean {
          // Original bean implementation
      }
      
  16. Creating inner beans in Spring XML configuration:

    • Description: Define inner beans within the scope of another bean.
    • XML Code:
      <bean id="outerBean" class="com.example.OuterBean">
          <property name="innerBean">
              <bean class="com.example.InnerBean"/>
          </property>
      </bean>
      
    • Java Code:
      public class OuterBean {
          private InnerBean innerBean;
      
          // Setter for innerBean
      }