Junior — Middle
What are the purpose and functions of beans in the context of a server or application?
sobes.tech AI
Answer from AI
In the context of a server or application, especially in Java and Spring, beans are objects managed by a container (for example, the Spring IoC container). They represent components of the application that are created, configured, and managed by the container throughout the application's lifecycle.
Main functions of beans:
- Encapsulation of business logic or services.
- Dependency management through Dependency Injection.
- Ensuring code reusability and modularity.
- Managing the lifecycle of objects (creation, initialization, destruction).
Example of defining a bean in Spring:
@Component
public class UserService {
public void createUser() {
// business logic for creating a user
}
}
The container will automatically create an instance of UserService and inject it where needed.