What Is a Spring Bean?

A Spring Bean is an object that is instantiated, configured, and managed by the Spring IoC (Inversion of Control) container. It represents a core component of a Spring application, and its lifecycle is controlled by the Spring framework.

Key Points: • Spring Beans are created and managed automatically by the Spring container. • Beans are typically defined using annotations such as @Component, @Service, @Repository, and @Controller, or through Java/XML configuration. • Spring handles dependency injection between beans, promoting loose coupling. • Bean lifecycle, initialization, and destruction can be managed by the framework. • Beans can have different scopes such as Singleton, Prototype, Request, and Session.

Example: In an e-commerce application, a UserService class can be defined as a Spring Bean. Spring creates the object, injects its dependencies, and makes it available throughout the application whenever required.

Code Example:

@Service
public class UserService {
    
    public void createUser() {
        System.out.println("User created");
    }
}

Interview Tip: A concise interview answer is:

"A Spring Bean is an object whose lifecycle is managed by the Spring container. Spring automatically creates, configures, and injects dependencies into beans, making application components loosely coupled and easier to maintain."