Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> @Configuration vs @Bean - onlinestudy.guru
Site icon onlinestudy.guru

@Configuration vs @Bean

In Spring Boot and the broader Spring Framework, @Configuration and @Bean are used to define and manage beans within the Spring container. They are closely related but serve different purposes and are used in different contexts.

@Configuration

Purpose:

Usage:

Key Features:

Example:

@Configuration
public class AppConfig {

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

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

In this example, AppConfig is a configuration class that defines two beans: myService and myRepository.

@Bean

Purpose:

Usage:

Key Features:

Example:

@Configuration
public class AppConfig {

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

In this example, the myService method is annotated with @Bean, meaning it will create and return an instance of MyServiceImpl, which Spring will manage.

Comparison and Relationship

Usage Scenarios

Example Integration

@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        // Configure and return the DataSource bean
        return new DataSource();
    }

    @Bean
    public MyService myService(DataSource dataSource) {
        // Inject DataSource into MyService and return the bean
        return new MyServiceImpl(dataSource);
    }
}

In this example, dataSource and myService are beans defined within the AppConfig configuration class. The myService bean method depends on the dataSource bean, and Spring will handle the dependency injection automatically.

Summary

By using @Configuration and @Bean, you can efficiently manage and configure your Spring application’s beans, ensuring a clean and modular approach to configuration.

Exit mobile version