Middle
What happens if you try to get the same bean multiple times in ApplicationContext?
sobes.tech AI
Answer from AI
By default, if a bean is defined in the ApplicationContext as a singleton (which is the default scope), each call to the getBean() method for that bean will return the same instance of the object. Spring manages the lifecycle of singleton beans by creating them once and caching them.
If the bean is defined with a different scope, such as prototype, then each call to getBean() will return a new instance of the object.
You can check the scope like this:
// Obtain ApplicationContext (for example, from SpringApplication.run())
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// Get the bean MyService (assuming it is defined)
MyService service1 = context.getBean(MyService.class);
MyService service2 = context.getBean(MyService.class);
// Compare references
System.out.println(service1 == service2);
If MyService has scope singleton, the output will be true. If prototype, the output will be false.
In the case of other scopes (request, session, application, websocket), the behavior depends on the execution context (for example, web request or session).