Sobes.tech
Senior

Tell me about ways to create beans in Spring

sobes.tech AI

Answer from AI

In Spring, there are several ways to create beans that manage the lifecycle and dependencies of objects:

  1. Annotations (@Component, @Service, @Repository, @Controller)

    • Classes are marked with the corresponding annotations.
    • Spring scans packages (component scanning) and automatically registers such classes as beans.
  2. Configuration classes with @Configuration and methods with @Bean

    • In a class annotated with @Configuration, methods marked with @Bean create bean instances.
    • Allows explicit description of bean creation and configuration.
  3. XML configuration

    • In older projects, beans are described in XML files using <bean> tags.
    • Rarely used now, but still supported.
  4. FactoryBean

    • Implementing the FactoryBean interface allows creating complex beans with custom logic.
  5. Programmatic creation via ApplicationContext

    • Beans can be created programmatically, but this is not a typical method.

Example using @Configuration and @Bean:

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

Thus, the choice of method depends on project requirements and development style.