What are Bean and BeanDefinition in Spring?
sobes.tech AI
Answer from AI
In Spring, a Bean is an object managed by the Spring container. The container creates, configures, and manages the lifecycle of these objects.
BeanDefinition is meta-information about a Bean that the container uses to create and configure the Bean. It contains:
- Bean class
- Scope (singleton, prototype, etc.)
- Constructors and arguments
- Properties for injection
- Initialization and destruction methods
In simpler terms, BeanDefinition describes how to create and configure a Bean, and the Bean is the object that has been created.
Example: if you have a class
public class UserService {
private UserRepository repo;
public UserService(UserRepository repo) {
this.repo = repo;
}
}
then the BeanDefinition will contain information about the UserService class, its constructor, and the UserRepository dependency, while the Bean is an instance of UserService created by the container.
The Spring container reads BeanDefinitions from configuration (XML, annotations, JavaConfig) and creates Beans based on them.