Spring Beans
Spring Beans Interview with follow-up questions
1. What is a Spring Bean?
A Spring Bean is simply an object that the Spring IoC container instantiates, configures, wires, and manages. The "bean" label just means the container owns this object's lifecycle and dependencies — there's nothing special about the class itself.
You tell Spring which objects are beans via:
- Stereotype annotations + component scanning —
@Component,@Service,@Repository,@Controller/@RestController. @Beanmethods inside a@Configurationclass (for third-party types you can't annotate).- (Legacy) XML `` definitions.
@Service // a bean discovered by scanning
class OrderService { ... }
@Configuration
class AppConfig {
@Bean RestClient restClient() { return RestClient.create(); } // explicit bean
}
Points worth adding: each bean has a scope (singleton by default — one shared instance) and a lifecycle the container manages (@PostConstruct/@PreDestroy). Once registered, beans are injected into one another by the container (preferably via constructor injection). In a Spring Boot app, beans are the unit of everything — controllers, services, repositories, and configuration are all beans.
Follow-up 1
How is a Spring Bean defined?
A Spring Bean is defined in the Spring configuration file or using annotations. In the configuration file, a bean is defined using the element, which specifies the class of the bean and any dependencies it has. Annotations can also be used to define a bean, such as @Component, @Service, @Repository, etc.
Follow-up 2
What is the lifecycle of a Spring Bean?
The lifecycle of a Spring Bean consists of several phases: instantiation, population of properties, and initialization. After initialization, the bean is ready to be used. During the lifecycle, the bean can also be destroyed, which allows for cleanup of resources.
Follow-up 3
How can you configure a Spring Bean?
There are several ways to configure a Spring Bean:
XML Configuration: Beans can be configured using XML in the Spring configuration file.
Annotation-based Configuration: Beans can be configured using annotations such as @Component, @Service, @Repository, etc.
Java-based Configuration: Beans can be configured using Java classes annotated with @Configuration and @Bean annotations.
Java Configuration with XML: Beans can be configured using a combination of XML and Java configuration.
Follow-up 4
What are the different scopes of a Spring Bean?
The different scopes of a Spring Bean are:
Singleton: Only one instance of the bean is created and shared across the application.
Prototype: A new instance of the bean is created every time it is requested.
Request: A new instance of the bean is created for each HTTP request.
Session: A new instance of the bean is created for each HTTP session.
Global Session: A new instance of the bean is created for each global HTTP session (used in a portlet context).
2. What are the different ways to configure a Spring Bean?
Three approaches, in roughly the order you'd reach for them today:
- Annotation-based (component scanning) — annotate classes with
@Component/@Service/@Repository/@Controllerand let Spring discover them. The most common style for your own code. - Java-based (
@Configuration+@Bean) — define beans explicitly in a config class. Type-safe, refactorable, and the right tool for third-party classes you can't annotate. - XML configuration — `` definitions in an XML file. Legacy; you'll see it in old codebases but it's rarely used for new projects.
@Configuration
class AppConfig {
@Bean
PaymentClient paymentClient(@Value("${pay.url}") String url) {
return new PaymentClient(url);
}
}
The 2026 framing interviewers want: annotations + Java config are the modern standard; XML is legacy. In Spring Boot, you mostly write @Component-style beans and let auto-configuration provide the infrastructure beans (DataSource, etc.), adding @Bean methods only when you need to customize or register third-party objects. Prefer constructor injection in whatever style you choose.
Follow-up 1
What is the difference between XML and annotation-based configuration?
The main difference between XML and annotation-based configuration is the way the bean configuration is defined.
In XML configuration, the bean configuration is defined in an XML file. The XML file contains the bean definitions with their properties and dependencies.
In annotation-based configuration, the bean configuration is defined using annotations. Annotations such as @Component, @Service, @Repository, and @Controller are used to mark the classes as beans.
XML configuration provides a more explicit and centralized way of configuring beans, while annotation-based configuration provides a more concise and flexible way of configuring beans.
Follow-up 2
Can you provide an example of each?
Sure! Here's an example of XML configuration:
Follow-up 3
Can you provide an example of each?
Sure! Here's an example of annotation-based configuration:
@Component
public class UserService {
@Autowired
private UserRepository userRepository;
// ...
}
@Repository
public class UserRepository {
@Autowired
private DataSource dataSource;
// ...
}
Follow-up 4
What are the advantages of using annotation-based configuration?
There are several advantages of using annotation-based configuration:
Concise and readable: Annotation-based configuration reduces the amount of boilerplate code required compared to XML configuration.
Type safety: Annotations provide compile-time type checking, reducing the chances of runtime errors.
Flexibility: Annotations allow for more flexible configuration options, such as conditional bean creation and dynamic bean wiring.
Integration with other frameworks: Annotation-based configuration is often used in conjunction with other frameworks, such as Spring MVC and Spring Data, making it easier to integrate different components of an application.
Better IDE support: IDEs provide better support for working with annotations, such as auto-completion and refactoring tools.
3. What are the different scopes of a Spring Bean?
Spring bean scopes control how many instances exist and how long they live:
singleton(default) — one shared instance per container, created eagerly at startup. The default for stateless services/repositories.prototype— a new instance every time the bean is requested/injected. Use for stateful, short-lived objects. (Note: the container does not manage a prototype's destruction.)
Web-aware scopes (in a web app):
request— one instance per HTTP request.session— one per HTTP session.application— one perServletContext.websocket— one per WebSocket session.
@Component @Scope("prototype")
class Calculation { ... }
The correction interviewers look for: "global session" is obsolete — it belonged to the old Portlet API, which Spring removed. Modern scopes are the ones above (application/websocket replaced the Portlet-era options). A classic gotcha to mention: injecting a prototype (or request-scoped) bean into a singleton captures a single instance — use a scoped proxy (proxyMode = TARGET_CLASS) or ObjectProvider/@Lookup to get a fresh one each time.
Follow-up 1
What is the default scope of a Spring Bean?
The default scope of a Spring Bean is singleton.
Follow-up 2
What is the difference between singleton and prototype scope?
The difference between singleton and prototype scope is:
Singleton scope creates only one instance of the bean and shares it across the entire application, while prototype scope creates a new instance of the bean every time it is requested.
Singleton beans are created when the application context is initialized, while prototype beans are created when they are requested.
Singleton beans are cached and reused, while prototype beans are not cached and a new instance is created every time.
Singleton beans can have state, while prototype beans are typically stateless.
Follow-up 3
Can you provide an example of when you would use each scope?
Sure! Here are some examples:
Singleton scope is commonly used for stateless beans, such as utility classes or service classes that don't maintain any state.
Prototype scope is useful when you want a new instance of a bean for each request, such as in a web application where each user session requires a separate instance of a bean.
Request scope is used when you want a new instance of a bean for each HTTP request, such as in a web application where each request requires a separate instance of a bean.
Session scope is used when you want a new instance of a bean for each HTTP session, such as in a web application where each user session requires a separate instance of a bean.
Global Session scope is similar to session scope, but used in a Portlet context where multiple users can share the same session.
4. What is the lifecycle of a Spring Bean?
The container drives a bean through these phases:
- Instantiation — the bean is created from its definition.
- Dependency injection — collaborators are wired in (constructor/setter/field).
- Aware callbacks &
BeanPostProcessor(before-init) — e.g. where AOP proxies/annotations are applied. - Initialization —
@PostConstruct, thenInitializingBean.afterPropertiesSet(), then a custominitMethod. BeanPostProcessor(after-init) — proxy wrapping finalized; bean is ready for use.- Destruction (singletons, on context shutdown) —
@PreDestroy, thenDisposableBean.destroy(), then a customdestroyMethod.
@Component
class ConnectionPool {
@PostConstruct void init() { /* open resources */ }
@PreDestroy void shutdown() { /* close resources */ }
}
Points interviewers reward: prefer the @PostConstruct/@PreDestroy annotations over the Spring-specific InitializingBean/DisposableBean interfaces (cleaner, no Spring coupling); destruction callbacks run only for singletons — Spring doesn't manage the full lifecycle of prototype beans; and the real extension point Spring uses internally is BeanPostProcessor, which is how AOP, transactions, and annotation processing get applied. Use init/destroy hooks for resource setup and cleanup.
Follow-up 1
What methods are called during the lifecycle of a Spring Bean?
During the lifecycle of a Spring Bean, the following methods can be called:
@PostConstruct: Annotated method that is called after the bean has been initialized.@PreDestroy: Annotated method that is called before the bean is destroyed.InitializingBean: Interface method that is called after the bean has been initialized.DisposableBean: Interface method that is called before the bean is destroyed.
These methods can be used to perform custom logic during the different phases of the bean's lifecycle.
Follow-up 2
How can you customize the lifecycle of a Spring Bean?
You can customize the lifecycle of a Spring Bean by using the following methods:
- Implementing the
InitializingBeanandDisposableBeaninterfaces and overriding their respective methods. - Annotating a method with
@PostConstructto perform initialization logic. - Annotating a method with
@PreDestroyto perform destruction logic. - Defining an
init-methodanddestroy-methodin the bean configuration XML file.
These methods allow you to add custom logic to be executed during the different phases of the bean's lifecycle.
Follow-up 3
What is the difference between init-method and @PostConstruct?
The main difference between init-method and @PostConstruct is the way they are defined and called:
init-method: This is a method defined in the bean configuration XML file using theinit-methodattribute. It is called after the bean has been instantiated and its dependencies have been injected.@PostConstruct: This is an annotated method that is called after the bean has been initialized. It can be used in conjunction with other annotations like@Autowiredor@Resourceto perform initialization logic.
In general, it is recommended to use @PostConstruct as it provides a more flexible and concise way to define initialization logic.
5. What are Spring Bean annotations?
Bean annotations are how you declare and configure beans without XML. Grouped by purpose:
Declaring beans (stereotypes, found by component scanning):
@Component— generic bean;@Service(business logic),@Repository(data access — also enables JDBC/JPA exception translation),@Controller/@RestController(web).
Defining beans explicitly:
@Configuration+@Bean— declare beans in a config class (great for third-party types).
Wiring & selecting:
@Autowired(injection),@Qualifier(pick among candidates),@Primary(default candidate),@Value(inject properties),@Lazy,@Profile.
Scope & lifecycle:
@Scope,@PostConstruct,@PreDestroy.
@Service
class PricingService {
PricingService(@Qualifier("eu") TaxRepository tax) { ... }
}
The framing that signals current knowledge: this annotation-driven style (with Java @Configuration) is the modern standard over XML, and @SpringBootApplication bundles @Configuration + @ComponentScan + @EnableAutoConfiguration. Stereotypes are functionally similar but semantically meaningful (and @Repository adds exception translation), so choose the one that fits the layer.
Follow-up 1
What is the purpose of the @Component annotation?
The @Component annotation is used to mark a class as a Spring bean. It is a generic stereotype annotation that can be used with any class. When a class is annotated with @Component, Spring will automatically detect and register it as a bean in the application context. This annotation is typically used for classes that do not fall into any other specific stereotype category, such as @Controller or @Service.
Follow-up 2
What is the difference between @Component and @Bean?
The @Component annotation is a generic stereotype annotation that can be used with any class, whereas the @Bean annotation is a method-level annotation that is used to explicitly declare a bean. When a class is annotated with @Component, Spring will automatically detect and register it as a bean, whereas with @Bean, the developer explicitly declares a method to create and configure a bean. Another difference is that @Component beans are singletons by default, whereas @Bean methods can be configured to create a new instance of the bean for each invocation.
Follow-up 3
What are some other important Spring Bean annotations and their uses?
Some other important Spring Bean annotations include:
- @Controller: Used to mark a class as a Spring MVC controller.
- @Service: Used to mark a class as a service component.
- @Repository: Used to mark a class as a data access component.
- @Autowired: Used to inject dependencies into a bean.
- @Qualifier: Used to specify which bean to inject when multiple beans of the same type are available.
- @Scope: Used to specify the scope of a bean, such as singleton or prototype.
- @PostConstruct: Used to specify a method that should be invoked after the bean has been constructed.
- @PreDestroy: Used to specify a method that should be invoked before the bean is destroyed.
6. What is the difference between @Component and @Bean?
Both register a bean in the container, but they apply at different places and for different cases:
@Component(and its stereotypes@Service/@Repository/@Controller) — annotates your own class so it's discovered by component scanning and auto-instantiated. Use it for classes you write and control.@Bean— annotates a method inside a@Configurationclass; the method explicitly constructs and returns the bean. Use it when you need full control over creation or when the type is third-party (you can't add@Componentto its source).
@Component // your class, found by scanning
class OrderService { ... }
@Configuration
class AppConfig {
@Bean ObjectMapper objectMapper() { // third-party type, built explicitly
return JsonMapper.builder().findAndAddModules().build();
}
}
The points interviewers reward: @Component is classpath-scanned (one bean per annotated class), while @Bean is declared programmatically (you decide constructor args, conditional creation, naming). Prefer @Component for your own beans and @Bean for library objects or anything needing custom wiring. Both end up as the same kind of container-managed bean.
Live mock interview
Mock interview: Spring Beans
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.