7 Ways to Create bean in Java Spring + Spring Boot

In Java, especially in the context of the Spring Framework, there are several ways to create and configure beans.

Beans are basically a java class which objects are managed by a container (e.g., the Spring IoC container). It handles their creation, configuration, and lifecycle.

Here are various ways to create beans in Java:

1). Using Constructor Injection:

  • Declare a class with a constructor.
  • Annotate the class with @Component or a related stereotype annotation.
  • Use @Autowired or XML configuration to inject dependencies into the constructor.
@Component
public class MyService {
    private final MyDependency dependency;

    @Autowired
    public MyService(MyDependency dependency) {
        this.dependency = dependency;
    }
}

2). Using Method Injection:

  • Define a method within a class.
  • Annotate the class with @Component or related stereotype annotations.
  • Annotate the method with @Bean.
  • Optionally, you can specify the bean’s name or other configuration properties.
@Configuration
public class MyConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

3). Using Factory Methods:

  • Define a class with a method that creates and configures the bean.
  • Annotate the class with @Configuration.
  • Use @Bean annotation to declare the factory method.
@Configuration
public class MyConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

4). Using XML Configuration:

  • Create an XML configuration file and define beans using <bean> elements.
<bean id="myBean" class="com.example.MyBean"/>

5). Using Component Scanning:

  • Annotate classes with @Component, @Service, @Repository, or other stereotype annotations.
  • Enable component scanning in the Spring configuration.
@Component
public class MyComponent {
    // ...
}

6). Using Java Configuration:

  • Define a class annotated with @Configuration.
  • Use @Bean annotations to declare beans and their configuration.
@Configuration
public class MyConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

7). Using FactoryBeans:

  • Implement the FactoryBean interface to create and configure a bean dynamically.
public class MyFactoryBean implements FactoryBean<MyBean> {
    @Override
    public MyBean getObject() {
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }
}

These are some common ways to create beans in Java, especially when working with the Spring Framework. The choice of which method to use depends on your specific requirements, architecture, and preferences.