How does Spring manage resources differently in a web application context?

In a web application, Spring manages resources through its IoC container, which centralizes the creation, configuration, and lifecycle of components like database connections, thread pools, and beans, rather than leaving each part of the app to manage its own. This differs from how a plain servlet app would typically wire things up manually and repeatedly.

Key Points: • The IoC container creates beans once (by default as singletons) and injects them wherever needed, avoiding redundant instantiation of expensive resources like connection pools. • Web-specific bean scopes — request and session — let Spring manage objects whose lifecycle should match a single HTTP request or a user's session, rather than living for the whole application. • Resource-heavy beans like DataSource or a RestTemplate/WebClient are configured once centrally and reused across the app instead of being created per request. • Spring's lifecycle callbacks (@PostConstruct, @PreDestroy, or DisposableBean) let resources be initialized and cleaned up predictably as the container starts and stops. • Auto-configuration in Spring Boot extends this further by wiring sensible defaults for resources like connection pools and thread pools based on what's on the classpath, reducing manual setup.

Example: A DataSource bean configured once in a Spring Boot app is shared by every repository and service that needs database access, instead of each class opening its own connection, which both centralizes configuration and avoids exhausting the database's connection limit.

Interview Tip: A concise interview answer is:

"Spring centralizes resource management through its IoC container, creating expensive beans like connection pools once as singletons and injecting them everywhere they're needed, instead of each class managing its own. It also adds web-specific request and session scopes, plus lifecycle callbacks like @PostConstruct and @PreDestroy, so resource setup and teardown stay predictable across the application."