Spring & Spring Boot Flashcards

(40 cards)

1
Q

What is the difference between Spring Boot and the traditional Spring Framework? How does Spring Boot simplify application development?

A

Spring Framework:
* Requires manual configuration (XML or Java-based).
* Developers must set up dependencies, servers, and project structure.

Spring Boot:
* Provides auto-configuration and embedded servers.
* Uses “starter” dependencies for common features.
* Minimal setup—just run the main class to start the app.
* Simplifies development by reducing boilerplate and configuration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can you imagine a case when you would not recommend using Spring (Boot)? What would you use instead and why?

A

Not recommended:
* For very simple or lightweight applications (e.g., small REST APIs, CLI tools) where Spring’s features are overkill.
* When fast startup and low memory usage are critical (e.g., serverless, microservices with strict resource limits).

Alternatives:
* Micronaut, Quarkus: Lightweight Java frameworks with faster startup and lower memory footprint.
* Plain Java with JAX-RS (Jersey), or frameworks like Spark Java: For minimalistic REST APIs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the @PostConstruct annotation do in Spring Boot?

A

Marks a method to run after the bean’s dependencies are injected and initialization is complete.

Used for initialization logic (e.g., setting up resources) after the bean is created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are starter dependencies in Spring Boot?

A

Predefined dependency packages that bundle commonly used libraries and configurations for specific tasks (e.g., web, data, security).

Simplify setup—just add a starter (like spring-boot-starter-web) and get all required dependencies automatically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the Spring Boot actuator?

A

A module that provides production-ready features for monitoring and managing applications.

Exposes endpoints for health checks, metrics, environment info, and more.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the main features of Spring?

A

Dependency Injection (DI): Manages object dependencies.

Aspect-Oriented Programming (AOP): Separates cross-cutting concerns (e.g., logging, security).

Data Access: Simplifies database operations (JDBC, ORM).

Transaction Management: Handles transactions across resources.

Model-View-Controller (MVC): Supports web application development.

Integration: Connects with other frameworks and technologies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is Dependency Injection useful for writing maintainable code?

A

Promotes loose coupling—classes depend on abstractions, not concrete implementations.

Makes code easier to test (can inject mocks/stubs).

Simplifies code changes and refactoring.

Improves reusability and flexibility.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a Spring Bean? Which bean scopes do you know?

A

Spring Bean: An object managed by the Spring container (created, configured, and wired automatically).

Bean scopes:
* Singleton (default): One instance per Spring container.
* Prototype: New instance each time requested.
* Request: One per HTTP request (web apps).
* Session: One per HTTP session (web apps).
* Application: One per ServletContext (web apps).
* Websocket: One per WebSocket session.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the DispatcherServlet?

A

The central front controller in Spring MVC.

Receives all HTTP requests, dispatches them to appropriate controllers, and returns responses.

Handles request routing, view resolution, and exception handling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does Spring Boot’s auto-configuration work, and what role does @EnableAutoConfiguration play?

A

Auto-configuration:
* Automatically configures beans and settings based on classpath contents and project properties.
* Reduces manual setup—just add dependencies, and Spring Boot configures them for you.

@EnableAutoConfiguration:
* Annotation that triggers auto-configuration.
* Usually included via @SpringBootApplication.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the central parts of Spring MVC?

A

DispatcherServlet: Front controller that routes requests.

Controller: Handles requests and returns responses or views.

Model: Holds data to be displayed or processed.

View: Renders the output (e.g., HTML, JSON).

ViewResolver: Maps view names to actual view implementations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is an interceptor and how is it different from a filter?

A

Interceptor:
* Works at the Spring MVC level (inside DispatcherServlet).
* Used for pre- and post-processing of controller requests (e.g., logging, authentication).
* Can access and modify request/response and handler objects.

Filter:
* Works at the Servlet level (before DispatcherServlet).
* Used for generic request/response processing (e.g., encoding, security).
* Cannot access Spring-specific objects like controllers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you explain the lifecycle of a Spring bean?

A
  1. Instantiation: Bean object is created.
  2. Populate Properties: Dependencies are injected.
  3. BeanNameAware/BeanFactoryAware: Bean gets aware of its name/factory (if implemented).
  4. Pre-initialization: BeanPostProcessor’s postProcessBeforeInitialization runs.
  5. Initialization: Custom init methods or @PostConstruct run.
  6. Post-initialization: BeanPostProcessor’s postProcessAfterInitialization runs.
  7. Ready to use: Bean is available for use.
  8. Destruction: On container shutdown, custom destroy methods or @PreDestroy run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the lifecycle hooks of a Spring bean?

A

Initialization hooks:
* @PostConstruct annotated method
* InitializingBean.afterPropertiesSet()
* Custom init method (specified in bean config)

Destruction hooks:
* @PreDestroy annotated method
* DisposableBean.destroy()
* Custom destroy method (specified in bean config)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can BeanPostProcessor be used to enhance the functionality of a bean?

A

Allows custom logic before and after bean initialization.

Can modify, wrap, or replace beans (e.g., add proxies, inject extra behavior).

Used for features like AOP, custom annotations, or validation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How is the @Transactional annotation implemented in Spring Core? Can a private method be annotated with @Transactional, and will it work as expected? What happens when a @Transactional method is called from another @Transactional method within the same class?

A

Implementation:
Uses proxies (AOP) to manage transactions around public methods.

Private methods:
Annotation won’t work as expected—proxies only intercept public methods.

Internal calls:
Calling a @Transactional method from another method in the same class bypasses the proxy, so transaction management won’t be applied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What proxy types exist in Spring, and what are the differences?

A

JDK Dynamic Proxy:
* Used when the bean implements at least one interface.
* Proxy implements the same interfaces as the target bean.

CGLIB Proxy:
* Used when the bean does not implement any interfaces.
* Proxy subclasses the target class (creates a subclass at runtime).

Difference:
* JDK proxy works with interfaces; CGLIB works with concrete classes.
* CGLIB cannot proxy final classes or methods.

18
Q

What is Inversion of Control (IoC), and how does Spring manage dependencies?

A

Inversion of Control (IoC):
Design principle where control of object creation and dependency management is transferred from the application code to a container.

Spring’s approach:
Spring IoC container creates, configures, and injects dependencies into beans automatically (using XML, annotations, or Java config).

19
Q

What are the differences between @Autowired, @Inject, and @Resource annotations?

A

@Autowired:
* Spring-specific; injects dependencies by type (default).
* Can be used on constructors, fields, or setters.

@Inject:
* From JSR-330 (Java standard); functionally similar to @Autowired.
* Injects by type.

@Resource:
* From JSR-250; injects by name (default), then by type if name not found.
* Can specify the bean name with the name attribute.

20
Q

What are the different types of Dependency Injection in Spring? When should each be used? Why is field injection not recommended?

A

Constructor Injection: Dependencies provided via constructor.
* Recommended: Ensures immutability, makes dependencies explicit, supports testing.

Setter Injection: Dependencies set via setter methods.
* Use when: Dependencies are optional or can change after object creation.

Field Injection: Dependencies injected directly into fields.
* Not recommended: Hides dependencies, makes testing and refactoring harder, breaks immutability.

21
Q

Can you explain the difference between@Component,@Service,@Repository, and@Controller? When would you use each, and how does Spring manage these beans?

A

@Component:
* Generic stereotype for any Spring-managed bean.
* Use for general-purpose beans.

@Service:
* Specialization of @Component for service-layer beans.
* Use for business logic/services.

@Repository:
* Specialization of @Component for data access objects (DAOs).
* Adds exception translation for persistence errors.

@Controller:
* Specialization of @Component for web controllers in Spring MVC.
* Handles HTTP requests and responses.

Spring management:
All are detected via component scanning and registered as beans in the application context.

22
Q

How would you handle circular dependencies in Spring? What strategies can resolve this, and what are the implications?

A

Circular dependency: When two or more beans depend on each other, causing a loop.

Strategies to resolve:
* Constructor injection: Not supported for circular dependencies—Spring will throw an error.
* Setter or field injection: Spring can resolve circular dependencies by injecting proxies or partially constructed beans.
* Refactor design: Break the dependency loop by introducing a third bean, using interfaces, or redesigning the relationships.
* Use @Lazy: Delays bean initialization to break the cycle.

Implications:
* Circular dependencies can make code harder to maintain and test.
* Prefer refactoring to avoid them when possible.

23
Q

How does Spring handle incoming HTTP requests?

A

DispatcherServlet receives all HTTP requests as the front controller.

HandlerMapping determines which controller should handle the request.

Controller processes the request and returns a response or view name.

ViewResolver maps the view name to an actual view (e.g., HTML, JSON).

Response is rendered and sent back to the client.

24
Q

What are the pros and cons of using Spring Boot?

A

Pros:
* Rapid development with minimal configuration.
* Embedded servers (no need for external deployment).
* Auto-configuration and starter dependencies simplify setup.
* Production-ready features (Actuator, metrics, health checks).

Cons:
* Less control over fine-grained configuration.
* Larger application size and memory footprint.
* May include unnecessary dependencies if not managed carefully.

25
How does Spring Type Conversion work?
Uses the ConversionService interface to convert between types (e.g., String to Integer). Automatically converts request parameters, properties, and bean fields as needed. Custom converters can be registered for complex types.
26
How does Spring Boot handle exceptions?
* Uses @ControllerAdvice and @ExceptionHandler to define global or controller-specific exception handling. * Automatically returns appropriate HTTP status codes and error messages for common exceptions. * Can customize error responses using ErrorController or by overriding default error handling.
27
How do you resolve bean conflicts in Spring using @Primary and @Qualifier?
@Primary: * Marks a bean as the default when multiple candidates exist for autowiring. @Qualifier: * Specifies exactly which bean to inject by name or qualifier value. Usage: * Use @Primary for the most common bean; use @Qualifier to select a specific bean when needed.
28
Can you explain the use of conditional annotations in Spring Boot?
Conditional annotations control bean creation based on certain conditions. Common examples: * @ConditionalOnProperty: Creates a bean if a specific property is set. * @ConditionalOnClass: Creates a bean if a class is present on the classpath. * @ConditionalOnMissingBean: Creates a bean only if another bean is not already defined. Used to enable/disable features or auto-configurations dynamically.
29
How do profiles work in Spring Boot and what are they used for?
* Profiles allow grouping of configuration and beans for different environments (e.g., dev, test, prod). * Use @Profile("profileName") to activate beans/configs only for specific profiles. * Activate profiles via application.properties (spring.profiles.active=dev) or command line. * Useful for environment-specific settings, like databases or logging.
30
How can you control transactions with the @Transactional annotation in Spring?
Apply @Transactional to methods or classes to manage transactions automatically. Can configure properties like: * Propagation: How transactions relate to existing ones (e.g., REQUIRED, REQUIRES_NEW). * Isolation: Level of data visibility between transactions. * Rollback rules: Specify which exceptions trigger rollback. * Read-only: Optimize for read operations. Ensures commit or rollback based on method success or failure.
31
How have you implemented authentication and authorization using Spring Security?
Authentication: * Configured user details (in-memory, JDBC, or custom UserDetailsService). * Used password encoders for secure password storage. Authorization: * Defined access rules with annotations (@PreAuthorize, @Secured) or in security config. * Configured URL-based access control in WebSecurityConfigurerAdapter or security filter chain. Other features: * Implemented JWT or OAuth2 for token-based security. * Used method-level security for fine-grained access control.
32
How have you used Spring Data for database access and query optimization?
Repository interfaces: Extended JpaRepository or CrudRepository for CRUD operations without boilerplate code. Custom queries: Used method naming conventions or @Query for custom JPQL/SQL queries. Pagination and sorting: Leveraged built-in support for efficient data retrieval. Query optimization: * Used projections and DTOs to fetch only required fields. * Applied query hints and fetch joins to reduce N+1 problems. * Enabled caching for frequently accessed data.
33
What are the benefits of using ORMs like Hibernate?
**Simplifies database access**: Maps Java objects to database tables automatically. **Reduces boilerplate code**: Handles CRUD operations and SQL generation. **Database independence**: Code is less tied to a specific database. **Advanced features**: Supports caching, lazy loading, and transaction management. **Improved maintainability**: Centralizes data mapping and relationships.
34
How do you handle the mapping between your application model and database model?
Use ORM frameworks (like Hibernate/JPA) with annotations (@Entity, @Table, @Column) to map Java classes and fields to database tables and columns. Define relationships using annotations (@OneToMany, @ManyToOne, etc.). Use DTOs or projections for custom data views and to decouple domain models from database schemas.
35
What is AOP (Aspect-Oriented Programming)? Why use it?
AOP: A programming paradigm that separates cross-cutting concerns (like logging, security, transactions) from business logic. Why use it? * Keeps code modular and clean. * Reduces duplication by centralizing common functionality. * Makes maintenance and updates easier.
36
What is the difference between @RestController and @Controller?
@Controller: * Used for web controllers that return views (e.g., HTML pages). * Methods typically return view names, and data is added to the model. @RestController: * Combines @Controller and @ResponseBody. * Methods return data (e.g., JSON, XML) directly in the HTTP response body—used for REST APIs.
37
What’s the difference between @ConditionalOnClass and @ConditionalOnBean?
@ConditionalOnClass: * Bean is created only if a specific class is present on the classpath. @ConditionalOnBean: * Bean is created only if a specific bean is already defined in the Spring context.
38
How do you configure and use property files in a Spring application? Can you share an example where externalized configuration improved maintainability?
Configuration: * Place property files (e.g., application.properties or application.yml) in the classpath. * Use @Value or @ConfigurationProperties to inject values into beans. * Externalize environment-specific settings (e.g., DB URLs, credentials). Example: * Moving database credentials and API keys to property files allows changing environments (dev, test, prod) without code changes, improving security and maintainability.
39
What are the differences between constructor injection and field injection in Spring? When would you use one over the other?
Constructor Injection: * Dependencies are provided via the class constructor. * Pros: Makes dependencies explicit, supports immutability, easier to test, works well with final fields. * Recommended for most cases. Field Injection: * Dependencies are injected directly into fields. * Cons: Hides dependencies, harder to test and refactor, doesn’t support immutability. * Use only for legacy code or quick prototypes.
40
How does Spring Boot work internally?
**Auto-configuration**: Scans the classpath and project settings to automatically configure beans and components. **Embedded server**: Starts an embedded web server (like Tomcat) so you can run apps as standalone Java processes. **Starter dependencies**: Provides pre-configured dependencies for common features (web, data, security). **Component scanning**: Detects and registers beans using annotations. **Externalized configuration**: Loads settings from property/YAML files and environment variables.