Backend Development (Java, Spring Boot) Flashcards

1
Q

What are the advantages of using Spring Boot over traditional Spring?

A

**Auto-configuration **Spring Boot simplifies the setup and development process by providing: Auto-configuration Spring Boot automatically configures your application based on the dependencies you’ve added, eliminating the need for extensive XML configuration or Java-based configuration.
**Standalone applications **- Spring Boot creates self-contained applications that include an embedded server (Tomcat, Jetty, or Undertow), allowing you to run your application without deploying WAR files to external servers.
Easy integration with databases: Spring Data JPA: Provides built-in ORM support for relational databases, reducing boilerplate code.
Auto-configuration: Detects database dependencies (e.g., MySQL, PostgreSQL, MongoDB) and configures them automatically.
Testing support - Comprehensive testing support including utilities and annotations for testing Spring Boot applications
Property file support - Simplified externalized configuration with application.properties or application.yml files.
Security Integration: Works seamlessly with OAuth2, JWT, and Keycloak for microservice authentication.Default security headers

  • Spring is everywhere
  • Spring is flexible
  • Inversion of Control (IoC) and Dependency Injection (DI)
  • IoC patten of Dependency Injection, freeing developers to focus on the application’s business logic
  • Spring is productive
  • Spring is fast
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain Spring Boot’s dependency injection.

A

Core Concepts
Spring Boot uses the Spring IoC (Inversion of Control) Container to manage object dependencies automatically.
y.
The IoC container is responsible for managing the lifecycle of objects (beans) and injecting their dependencies.

It’s a way for objects to receive their dependencies, rather than creating them themselves.
Here’s a breakdown
Beans: Java objects managed by the Spring IoC container are called beans.

Dependency Injection:
Annotations
It allows developers to declare dependencies using annotations like @Autowired, @Component, @Service, and @Repository, reducing manual object creation.
Configuration

@Configuration classes define beans with @Bean methods
Java-based configuration has largely replaced XML configuration

Advantages in Spring Boot
Auto-configuration: Spring Boot automatically configures beans based on the dependencies in your classpath
Component scanning: Automatically detects and registers beans from your application’s packages
Conditional beans: Creates beans only when certain conditions are met
Profiles: Allows different bean configurations for different environments

Spring Boot’s dependency injection (DI) is a core concept that significantly simplifies application development by promoting loose coupling and testability. It’s a way for objects to receive their dependencies, rather than creating them themselves. Here’s a breakdown:

What is Dependency Injection?

In traditional programming, objects often create their own dependencies (other objects they need to function). This leads to tight coupling, making code harder to maintain, test, and reuse. DI reverses this process. Instead of an object creating its dependencies, those dependencies are “injected” into the object from an external source.

Spring Boot’s Role in Dependency Injection:

Spring Boot, built on the Spring Framework, heavily leverages DI through its Inversion of Control (IoC) container. The IoC container is responsible for managing the lifecycle of objects (beans) and injecting their dependencies.

Key Concepts:

Beans: In Spring, objects managed by the IoC container are called beans.
IoC Container (Application Context): This is the heart of Spring’s DI. It creates, configures, and manages beans.
Dependency Injection: The process of providing an object with its dependencies.
Types of Dependency Injection in Spring Boot:

Constructor Injection:

Dependencies are injected through the constructor of the class.
This is the recommended approach as it ensures that the object is created with all its required dependencies.
Example:
Java

@Component
public class MyService {
private final MyRepository myRepository;

@Autowired // Optional in recent Spring versions
public MyService(MyRepository myRepository) {
    this.myRepository = myRepository;
}

// ... methods using myRepository ... } Setter Injection:

Dependencies are injected through setter methods.
Less common than constructor injection, but useful for optional dependencies.
Example:
Java

@Component
public class MyService {
private MyRepository myRepository;

@Autowired
public void setMyRepository(MyRepository myRepository) {
    this.myRepository = myRepository;
}

// ... methods using myRepository ... } Field Injection:

Dependencies are injected directly into fields using the @Autowired annotation.
Generally discouraged because it makes testing more difficult and can lead to runtime exceptions if dependencies are not properly injected.
Example:
Java

@Component
public class MyService {
@Autowired
private MyRepository myRepository;

// ... methods using myRepository ... } Benefits of Spring Boot's Dependency Injection:

Loose Coupling: Objects are not tightly coupled to their dependencies, making code more flexible and maintainable.
Testability: Dependencies can be easily mocked or stubbed during testing, simplifying unit testing.
Reusability: Beans can be reused in different parts of the application.
Maintainability: Changes to dependencies do not require changes to the objects that use them.
Configuration: Spring Boot’s auto-configuration simplifies the process of configuring dependencies.
How it Works:

Component Scanning: Spring Boot scans the application’s classpath for classes annotated with @Component, @Service, @Repository, and @Controller.
Bean Creation: The IoC container creates instances of these classes (beans).
Dependency Resolution: The container resolves dependencies by matching bean types and injecting them into the appropriate objects.
Bean Lifecycle: The container manages the lifecycle of beans, including creation, initialization, and destruction.

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

What is the difference between @RestController and @Controller?

A

@Controller is used for MVC applications and returns views (HTML, JSP, etc.).
@RestController is a combination of @Controller + @ResponseBody, automatically serializing responses to JSON/XML.

@Controller : used to declare common web controllers that can return HTTP responses
@RestController: used to create controllers for REST APIs that can return JSON responses.

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

What is the difference between Component, @Repository & @Service annotations in Spring? Why do we use different annotations?

A

: Spring provides stereotype annotations to define different types of Spring-managed beans. The three main annotations are:
1. @Component (Generic Component)
o The most generic annotation used to define a Spring-managed bean.
o It is a parent annotation of @Repository and @Service.
o Can be used for any component that does not fit into specific layers like repositories or services.
o Example:
o @Component
o public class UtilityHelper {
o public String processData(String input) {
o return input.toUpperCase();
o }
}
2. @Repository (DAO Layer)
o Specialized annotation for Data Access Objects (DAO).
o Helps Spring recognize that the class interacts with a database.
o Provides automatic exception translation (converts database exceptions into Spring DataAccessException).
o Example:
o @Repository
o public class UserRepository {
o @PersistenceContext
o private EntityManager entityManager;
o
o public User findById(Long id) {
o return entityManager.find(User.class, id);
o }
}
3. @Service (Business Logic Layer)
o Used for service layer classes that contain business logic.
o Provides better readability, explicitly indicating that the class performs business operations.
o Example:
o @Service
o public class UserService {
o private final UserRepository userRepository;
o
o public UserService(UserRepository userRepository) {
o this.userRepository = userRepository;
o }
o
o public User getUserDetails(Long id) {
o return userRepository.findById(id);
o }
}

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

Why do we use different annotations?

A

Code organization & readability: Helps developers understand the purpose of each class.

Spring’s automatic bean scanning: Spring can detect different components and organize the application accordingly.

Exception handling: @Repository provides built-in exception translation for database errors.

Separation of concerns: @Service ensures that business logic is separate from data access.

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

How do you secure a REST API in Spring Boot?

A

Use Spring Security with JWT authentication.
We are using Json web tocken to secure our Springboot project
Implement OAuth2 for secure access control.
Prevent CSRF (Cross-Site Request Forgery) attacks.
Use role-based authorization with @PreAuthorize.

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

How are transactions handled in Spring Boot?

A
  • In Spring Boot, transactions are managed using the @Transactional annotation:
    @Service
    public class PaymentService {
    @Autowired
    private AccountRepository accountRepository;@Transactional
    public void transferMoney(Long senderId, Long receiverId, Double amount) {
    accountRepository.decreaseBalance(senderId, amount);
    accountRepository.increaseBalance(receiverId, amount);
    }
    }
  • If an exception occurs, Spring automatically rolls back the transaction.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Security Integration in Spring Boot

A

Security Integration in Spring Boot
Spring Boot offers robust security integration through several key features:

Spring Security Starter - The spring-boot-starter-security dependency automatically configures basic security features with sensible defaults including form-based authentication, CSRF protection, and session fixation protection.

Autoconfigured Security - When the security starter is added, Spring Boot automatically secures all HTTP endpoints with basic authentication, requiring minimal code to get started.

Custom Security Configuration - Despite the defaults, you can easily customize security by extending the WebSecurityConfigurerAdapter class or using the newer component-based security configuration.

OAuth2 Support - Spring Boot provides dedicated starters for OAuth2 client (spring-boot-starter-oauth2-client) and resource server (spring-boot-starter-oauth2-resource-server) implementations.

JWT Authentication - Built-in support for JSON Web Tokens through Spring Security’s JWT libraries with simplified configuration.

Method Security - Annotation-based security like @PreAuthorize and @Secured is easily enabled with @EnableMethodSecurity.
Actuator Security - Management endpoints are automatically secured, with configurable access levels through properties.

CORS Configuration - Simple cross-origin resource sharing setup through properties or programmatic configuration.

Content Security Policy - Support for CSP headers to prevent XSS attacks.

User Store Integration - Easy integration with various user stores including in-memory, JDBC, JPA, LDAP, and custom UserDetailsService implementations.
Security Testing - Comprehensive testing support with annotations like @WithMockUser and @WithUserDetails.

WebFlux Security - Support for securing reactive applications built with Spring WebFlux.
Property-based Configuration - Many security settings can be configured through application.properties or application.yml files.

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

WebFlux Security in Spring Boot

A

WebFlux Security is Spring’s security solution specifically designed for reactive applications built with Spring WebFlux. Unlike traditional Spring MVC security, WebFlux Security is built on reactive principles to support non-blocking, asynchronous request processing.
Key features of WebFlux Security include:

Reactive Authentication - Provides non-blocking authentication mechanisms compatible with the reactive programming model.

Security WebFilter Chain - Uses reactive WebFilter instances rather than traditional Servlet filters to apply security rules.

Reactive Method Security - Supports securing methods with annotations while maintaining the reactive nature of the application.

Publisher-based Authorization - Authorization decisions work with reactive types like Mono and Flux.
Reactive Context Integration - Seamlessly integrates with the reactive context to propagate security information across asynchronous boundaries.

OAuth2/OIDC Support - Includes reactive implementations of OAuth2 login, client, and resource server functionality.

CSRF Protection - Provides CSRF protection specifically designed for reactive applications.
Configuration Model - Uses a dedicated ServerHttpSecurity configuration class instead of the traditional HttpSecurity.

Coroutines Support - Works well with Kotlin coroutines for building reactive applications.

To implement WebFlux Security, you typically:

Add the spring-boot-starter-security dependency along with spring-boot-starter-webflux

Create a SecurityWebFilterChain bean to define your security rules

Configure authentication and authorization in a reactive manner

This approach ensures security doesn’t become a blocking bottleneck in otherwise non-blocking reactive applications.

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

Spring applications can be configured using:

A

XML Configuration: Beans and their dependencies are defined in XML files.

Annotation-Based Configuration: Annotations like @Component, @Autowired, etc., are used to define beans and their dependencies.

Java-Based Configuration: Beans are defined using Java classes and methods annotated with @Configuration and @Bean.

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

Explain the difference between XML-based configuration, annotation-based configuration, and Java-based configuration.

A

Feature XML Configuration Annotation-Based Configuration Java-Based Configuration
Syntax XML tags and attributes Annotations in Java code Java classes and methods
Verbosity More verbose Less verbose Can be less verbose
Type Safety No type safety Some type safety Full type safety
Refactoring Refactoring can be error-prone Refactoring is easier Refactoring is easiest
Flexibility Less flexible More flexible Most flexible

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

Explain the lifecycle of a Spring bean.

A

The Spring bean lifecycle consists of several stages:

Instantiation: The bean is created.
Population: Dependencies are injected.
Initialization: Any initialization methods are called (e.g., @PostConstruct).
Destruction: Any cleanup methods are called before the bean is destroyed (e.g., @PreDestroy).

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

What are Spring scopes, and how do they work

A

Singleton: Only one instance of the bean is created per Spring container (default).

Prototype: A new instance is created each time the bean is requested.

Request: A new instance is created for each HTTP request.

Session: A new instance is created for each HTTP session.

Application: A new instance is created per ServletContext.

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

What are the advantages and disadvantages of using XML configuration versus annotation-based or Java-based configuration?

A

XML Configuration:

Advantages: Clear separation of configuration from code, easier to understand for beginners.
Disadvantages: More verbose, less type-safe, refactoring can be error-prone.

Annotation-Based Configuration:

Advantages: Less verbose, some type safety, easier refactoring.
Disadvantages: Can become cluttered with annotations, less explicit than XML.

Java-Based Configuration:

Advantages: Full type safety, most flexible, best for complex configurations.
Disadvantages: Can be more complex for beginners, requires more Java knowledge.

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

How do you configure and use Application Listeners and Event publishing?

A

Application Listeners: Implement the ApplicationListener interface to listen for specific events published within the Spring application context.
Event Publishing: Use the ApplicationEventPublisher to publish custom events.

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

How would you configure a database connection in a Spring application?

A

JDBC: Define a DataSource bean and provide connection details (URL, username, password).

JPA/Hibernate: Configure an EntityManagerFactory and provide database connection details.

Spring Data JPA: Use Spring Data JPA repositories to simplify database interactions.

17
Q

What is unit testing, and why is it important in Spring Boot?

A

Unit testing is a software testing method where individual units or components of a program are tested. In Spring Boot, this typically means testing individual classes or methods in isolation. It’s important because it:
Helps identify bugs early in the development cycle.
Ensures that individual components work as expected.
Facilitates code refactoring by providing a safety net.
Improves code quality and maintainability.

18
Q

What are the common testing annotations used in Spring Boot unit tests?

A

@Test: Marks a method as a test method.
@BeforeEach (or @Before in JUnit 4): Executes before each test method.
@AfterEach (or @After in JUnit 4): Executes after each test method.
@Mock: Creates a mock object for dependency injection.
@InjectMocks: Injects mock objects into the target class.
@ExtendWith(MockitoExtension.class): Enables Mockito features.
@ExtendWith(SpringExtension.class) or @SpringBootTest: provides Spring context support. However, for unit tests, you should try to avoid @SpringBootTest.

19
Q
  1. What are common bottlenecks in Spring Boot applications?
A

Common bottlenecks include:

Database Performance: Slow queries, inadequate indexing, connection pool exhaustion.

Network Latency: Delays in external service calls, inefficient data transfer.

CPU Utilization: Excessive processing, inefficient algorithms, thread contention.

Memory Leaks/Garbage Collection: Insufficient heap size, object retention issues.

I/O Bottlenecks: Slow disk access, inefficient file handling.

Inefficient Code: Poorly written algorithms, unoptimized loops, excessive object creation.

20
Q

How can you identify bottlenecks in a Spring Boot application?

A

Profiling Tools: VisualVM, JProfiler, YourKit to monitor CPU, memory, and thread activity.

Metrics and Monitoring: Spring Boot Actuator,

Prometheus, Grafana to track application performance.

Logging: Detailed logging to identify slow operations and errors.

Database Query Analysis: Tools like EXPLAIN in SQL to analyze query performance.

Load Testing: Tools like JMeter or Gatling to simulate heavy traffic and identify performance issues.

Thread Dumps: Analyzing thread dumps to identify thread contention or deadlocks.

21
Q

What are some strategies to address database bottlenecks in Spring Boot?

A

Optimize Queries: Use indexes, avoid SELECT *, rewrite slow queries.

Connection Pooling: Configure an efficient connection pool (e.g., HikariCP).

Caching: Implement caching (e.g., Redis, Caffeine) to reduce database load.

Database Tuning: Optimize database configuration, increase resources.

Batch Processing: Use batch processing for large data operations.

Read Replicas: offload read operations to read replicas.

22
Q

Key takeaways for Bottleneck solving:

A

Monitoring is essential.

Database and memory are common problem areas.

Asynchronous processing and caching are powerful tools.

Profiling tools are invaluable for deep analysis.