Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

How to Create a Spring Bean in 3 Different Ways?

In Spring Framework, beans are the objects that form the backbone of your application and are managed by the Spring IoC container. There are primarily three ways to configure and create a Spring Bean:

  1. XML Configuration:

    Before the rise of annotations, XML was the primary way of configuring Spring Beans. Here's how to do it:

    • Define the bean in spring-config.xml (or any other XML file name you might be using):

      <bean id="exampleBean" class="com.example.ExampleBean">
          <!-- You can set properties or dependencies here -->
          <property name="propertyName" value="propertyValue"/>
      </bean>
      
    • In your application, you'll load the context from this XML:

      ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
      ExampleBean exampleBean = context.getBean(ExampleBean.class);
      
  2. Annotation-based Configuration:

    You can use annotations directly in your Java classes to specify component and configuration information. This method reduces (or potentially eliminates) the need for XML configuration:

    • Annotate your class with @Component (or @Service, @Repository, @Controller depending on the use case):

      @Component
      public class ExampleBean {
          // class body...
      }
      
    • Make sure to enable component scanning by adding context:component-scan in your XML or @ComponentScan in your Java Config:

      @Configuration
      @ComponentScan(basePackages = "com.example")
      public class AppConfig {
      }
      
    • Then you can autowire this bean in other components:

      @Autowired
      private ExampleBean exampleBean;
      
  3. Java-based Configuration:

    Instead of using XML to describe a bean wiring, you can move bean configuration into one or more Java-based configuration classes:

    • Create a configuration class:

      @Configuration
      public class AppConfig {
          @Bean
          public ExampleBean exampleBean() {
              return new ExampleBean();
          }
      }
      
    • Beans defined in such a way can be retrieved and used just like the beans defined using other methods:

      ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
      ExampleBean exampleBean = context.getBean(ExampleBean.class);
      

Each method has its own advantages, and the best one often depends on the specific needs of your project. In modern Spring applications, annotation-based and Java-based configurations are more popular due to their concise nature and better integration with Java language features.

    <!-- applicationContext.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">
            <!-- Set properties or dependencies here -->
        </bean>
    
    </beans>
    
      @Configuration
      public class AppConfig {
      
          @Bean
          public MyBean myBean() {
              // Instantiate and configure MyBean
              return new MyBean();
          }
      
      }
      
        <!-- applicationContext.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">
                <!-- Set properties or dependencies here -->
            </bean>
        
        </beans>
        
          @Component
          public class MyBean {
              // Class implementation
          }
          
          <!-- applicationContext.xml -->
          <beans xmlns="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:context="http://www.springframework.org/schema/context"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans
                                     http://www.springframework.org/schema/beans/spring-beans.xsd
                                     http://www.springframework.org/schema/context
                                     http://www.springframework.org/schema/context/spring-context.xsd">
          
              <context:component-scan base-package="com.example"/>
          
          </beans>
          
            @Configuration
            public class AppConfig {
            
                @Bean
                public MyBean myBean() {
                    // Instantiate and configure MyBean
                    return new MyBean();
                }
            
            }