Sobes.tech
Junior

What are beans in the context of Java and Spring?

sobes.tech AI

Answer from AI

In the context of Java and Spring, a bean is an object managed by the Spring IoC (Inversion of Control) container.

Key points:

  • Object: This is any typical Java object.
  • Spring Management: The Spring Container is responsible for:
    • Creating bean instances.
    • Configuration (dependency injection).
    • Managing the lifecycle (initialization, usage, termination).
  • Configuration: Beans are defined via XML, annotations (@Component, @Service, @Repository, @Controller, @Bean), or Java-based configuration.
  • States: Most often, beans are singletons within the Spring Container by default, but they can also have other scopes: prototype, request, session, and global session.

Example of defining a bean using the @Component annotation:

// Class recognized by Spring Container as a bean
@Component
public class MyService {

    // Dependency injected by Spring
    private final MyRepository myRepository;

    // Constructor for dependency injection
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    public void doSomething() {
        myRepository.getData();
    }
}

Example of defining a bean using Java-based configuration:

// Configuration class
@Configuration
public class AppConfig {

    // Method that declares a bean
    @Bean
    public MyService myService(MyRepository myRepository) {
        return new MyService(myRepository);
    }

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

Beans form the backbone of your Spring application, ensuring component connectivity and manageability.