Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring @Bean Annotation with Example

The @Bean annotation is a method-level annotation in Spring's core framework, which indicates that a method produces a bean to be managed by the Spring container. It's a cornerstone of Java-based configuration in Spring, allowing you to define and configure beans programmatically as opposed to XML-based configuration.

When used within a class annotated with @Configuration, @Bean methods create and return objects that are registered as beans in the Spring application context.

Example:

Consider a simple example where we have a service that depends on a repository. We'll configure these beans using Java configuration and the @Bean annotation.

  • Defining Classes:
// A simple repository class
public class MyRepository {
    // repository methods here
}

// A service class with a dependency on the repository
public class MyService {
    private final MyRepository myRepository;

    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // service methods here
}
  • Java Configuration:

Instead of using XML configuration, you can define and wire these beans using Java-based configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public MyRepository myRepository() {
        return new MyRepository();
    }

    @Bean
    public MyService myService() {
        return new MyService(myRepository());
    }
}

In the above configuration:

  • The AppConfig class is annotated with @Configuration, signaling that it's a source of bean definitions.
  • The myRepository() method is annotated with @Bean, indicating that its return value (an instance of MyRepository) should be registered as a bean in the Spring application context.
  • The myService() method is also annotated with @Bean, and it produces an instance of MyService that's wired with the MyRepository bean.
  • Using the Beans:

To make use of these beans, you'd typically bootstrap your application using an AnnotationConfigApplicationContext:

public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        
        MyService myService = context.getBean(MyService.class);
        // Use the myService instance
    }
}

Additional Points:

  • Bean Names: By default, the name of the bean is the name of the method annotated with @Bean. You can override this default name by providing a name (or names) to the @Bean annotation, like @Bean(name = "customBeanName").

  • Bean Scope: By default, beans are singleton scoped. However, you can change the scope using the @Scope annotation, for example, @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) for prototype scope.

  • Lifecycle Callbacks: You can use the initMethod and destroyMethod attributes of the @Bean annotation to specify methods to be called post-construction and pre-destruction, respectively.

In summary, the @Bean annotation simplifies the process of defining and wiring beans in Spring without using XML configuration, allowing a more programmatic and type-safe approach to configuration.

  1. Creating beans with @Bean annotation in Spring:

    • Use the @Bean annotation to declare a method that produces a bean. Spring manages the lifecycle of the bean.
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  2. JavaConfig with @Bean in Spring framework:

    • JavaConfig uses the @Configuration and @Bean annotations to define beans. It's an alternative to XML configuration.
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  3. Using @Bean for manual bean definition in Spring:

    • Manually define beans using the @Bean annotation in a configuration class. This approach is useful for non-component classes.
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  4. Configuration classes and @Bean in Spring:

    • Configuration classes use the @Configuration annotation to indicate that they contain bean definitions. Beans are created using the @Bean annotation.
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  5. Customizing bean creation with @Bean annotation:

    • Customize the creation of beans using the @Bean annotation, providing additional configuration options.
    @Configuration
    public class AppConfig {
    
        @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  6. Scopes and lifecycles with @Bean in Spring:

    • Specify bean scopes and lifecycles using the @Scope and @PostConstruct/@PreDestroy annotations within a @Bean method.
    @Configuration
    public class AppConfig {
    
        @Bean
        @Scope("prototype")
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  7. Conditional bean creation with @Bean in Spring:

    • Use the @Conditional annotation with @Bean to conditionally create beans based on specific conditions.
    @Configuration
    public class AppConfig {
    
        @Bean
        @Conditional(MyCondition.class)
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  8. Injecting dependencies with @Bean annotation example:

    • Inject dependencies into beans using the @Bean annotation. Dependencies are automatically resolved by Spring.
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyDependency myDependency() {
            return new MyDependency();
        }
    
        @Bean
        public MyBean myBean(MyDependency dependency) {
            return new MyBean(dependency);
        }
    }