Junior — Middle
Can you explain the principle of how getBean() works in the context of Spring container?
sobes.tech AI
Answer from AI
The getBean() method in Spring is used to obtain an instance of a component (bean) from the Spring container.
The Spring container manages the lifecycle and dependencies of objects declared as beans. When you call getBean(), the container searches for a bean by name or type and returns its instance.
If the bean has not yet been created (for example, during lazy initialization), the container will create it, inject all dependencies, and return the ready object.
Example usage:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
MyService service = context.getBean(MyService.class);
Here, getBean() returns an object of type MyService managed by Spring. This allows for inversion of control and dependency injection, simplifying configuration and testing of applications.