0% found this document useful (0 votes)
2 views56 pages

SpringBoot & Spring Notes 1

The document explains Inversion of Control (IoC) and Dependency Injection (DI) in the context of the Spring framework, highlighting how Spring manages object creation and dependency management. It covers various types of dependency injection, the advantages of using IoC and DI, and provides insights into Spring Boot's configuration, layered architecture, and JDBC integration. Additionally, it includes common interview questions related to these topics.

Uploaded by

ritesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views56 pages

SpringBoot & Spring Notes 1

The document explains Inversion of Control (IoC) and Dependency Injection (DI) in the context of the Spring framework, highlighting how Spring manages object creation and dependency management. It covers various types of dependency injection, the advantages of using IoC and DI, and provides insights into Spring Boot's configuration, layered architecture, and JDBC integration. Additionally, it includes common interview questions related to these topics.

Uploaded by

ritesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

========================================================

IoC (Inversion of Control) & DI (Dependency Injection)


========================================================

1) What is IoC?
- IoC = Inversion of Control.
- It means: Instead of programmer creating and controlling objects,
Spring container takes control and manages object creation.
- Programmer "inverts" control to the framework (Spring).
Example:
Normal Java → "new Student()"
Spring IoC → Container creates Student bean and gives it to you.

2) What is DI?
- DI = Dependency Injection.
- It is a type of IoC where Spring injects the dependencies
(objects required by a class) instead of creating them manually.
- Means: If Class A needs Class B, Spring injects B into A.
Example:
Class Car needs Engine.
Instead of → Car car = new Car(new Engine());
Spring does → @Autowired Engine engine; (injected automatically).
3) How it Works in Spring
- Spring IoC Container (ApplicationContext or BeanFactory) manages beans.
- Reads configuration (XML, Annotations, or Java Config).
- Creates objects (beans), maintains their lifecycle.
- Injects dependencies (via constructor, setter, or field injection).
Types of Injection:
a) Constructor Injection (@Autowired on constructor)
b) Setter Injection (@Autowired on setter)
c) Field Injection (@Autowired directly on field)
4) Why use IoC & DI?
- Loose Coupling: Classes depend on abstractions, not concrete implementations.
- Reusability: Same service bean can be reused.
- Easier Testing: Mocks can be injected easily.
- Centralized Config: Beans managed in one place (container).
- Maintainability: Changing dependency does not require code changes everywhere.

5) Real Life Analogy


- Think of Electricity.
* Without IoC: Each device generates its own electricity.
* With IoC: Power Station (Spring Container) provides electricity (objects).
* Device (class) just consumes it → Dependency Injection.

6) Interview Questions & Answers


Q1: What is the difference between IoC and DI?
A1: IoC is the principle (container controls object creation).
DI is the way to achieve IoC (injecting dependencies).
Q2: What are different types of Dependency Injection?
A2: Constructor Injection, Setter Injection, Field Injection.
Q3: Which injection type is recommended and why?
A3: Constructor Injection (ensures immutability & easier testing).
Q4: What is the IoC Container in Spring?
A4: It is the core of Spring Framework that manages beans.
Examples: BeanFactory, ApplicationContext.
Q5: What is the difference between BeanFactory and ApplicationContext?
A5: BeanFactory → Basic container, lazy initialization.
ApplicationContext → Advanced container, eager init, supports AOP, events, i18n.
Q6: What are the advantages of Dependency Injection?
A6: Loose coupling, easy testing, better maintainability.
Q7: Can we achieve IoC without DI?
A7: Yes, IoC is broader. DI is one implementation. Example: Event listeners also use IoC.
Q8: How does @Autowired work internally?
A8: Spring scans context, finds a matching bean by type/name, and injects it into the dependent class.
======================================================

SPRING BEANS & DEPENDENCY INJECTION NOTES


======================================================

1. Spring Bean XML


- Beans are defined in XML using <bean>.
- Use: Configure objects outside Java code.
2. Object Creation
- IoC container creates/manages objects.
- Advantage: No "new" keyword, central control.
3. Setter Injection
- Use <property> to inject values via setter.
- Advantage: Flexible, can change values easily.
4. ref Attribute
- Links another bean by id.
- Use: To reuse objects across beans.
5. Constructor Injection
- Use <constructor-arg> to inject values.
- Advantage: Ensures required values at creation.
6. Creating Interface
- Define interface + multiple implementations.
- Advantage: Loose coupling, easy to extend.
7. Autowiring
- byName → Match property name with bean id.
- byType → Match property type with bean class.
- Advantage: Reduces manual wiring.
8. Primary Bean
- primary="true" → default bean if multiple exist.
- Use: Avoids "NoUniqueBeanDefinitionException".
9. Lazy Init
- lazy-init="true" → Bean created only when needed.
- Advantage: Saves memory, faster startup.
10. Inner Bean
- Define a bean inside another bean’s <property>.
- Use: For small, private helper objects.
11. Get Bean by Type
- [Link]([Link]) → fetch by type.
- Use: Cleaner than always using ids.

Overall Purpose:

- Loose coupling
- Easy configuration
- Reuse of components
- Flexible and testable design

Common Interview Questions & Answers:


Q1. Difference between Setter & Constructor Injection?
- Setter → Optional dependencies, flexible, can change later.
- Constructor → Mandatory dependencies, ensures all values at object creation.
Q2. What is Autowiring and its types?
- Autowiring automatically injects dependencies.
- Types: byName (match property name with bean id),
byType (match property type with bean class).
Q3. When to use Primary Bean?
- When multiple beans of same type exist → mark one as primary
so Spring knows which one to inject by default.
Q4. Why use Lazy Init?
- To save memory and improve startup time → bean is created only when actually needed.
Q5. Difference between ref attribute and Inner Bean?
- ref → Injects an already defined bean by its id (shared bean).
- Inner Bean → Define a bean inside another bean’s property (private bean, not reusable).
======================================================

SPRING BOOT: JAVA-BASED CONFIGURATION NOTES


======================================================

1. @Configuration + @ComponentScan
- @Configuration → marks AppConfig as a config class.
- @ComponentScan("[Link]") → auto-detects @Component classes.
- Use: Replace XML config with pure Java code.
2. @Bean Method
- Defines bean manually in Java class.
- Example: @Bean public Alien alien() { return new Alien(); }
- Bean name = method name (can override with @Bean(name="x")).
3. Bean Name
- Default → method name (e.g. alien(), desktop()).
- Custom → @Bean(name={"alias1","alias2"}).
4. Scope Annotation
- Default → singleton (one object per container).
- @Scope("prototype") → new object every time.
- Use: Choose between shared or new objects.
5. @Autowired
- Spring auto-injects dependency.
- Can be used on field, setter, or constructor.
- Field injection → directly on property.
- Setter injection → on setter method.
- Constructor injection → on constructor.
6. @Primary and @Qualifier
- @Primary → default bean if multiple same-type beans exist.
- @Qualifier("beanName") → choose exact bean to inject.
- Use: Resolve conflicts in dependency injection.
7. Component Stereotype Annotations
- @Component → generic Spring-managed class.
- @Service → business logic class.
- @Repository → DAO (data access) class.
- @Controller / @RestController → web layer.
- Use: Auto-detect and register beans via scanning.

8. @Value Annotation
- Injects literal values into fields.
- Example: @Value("21") private int age;

USES / ADVANTAGES
- No XML → pure Java-based configuration.
- Cleaner and type-safe.
- Easy testing and refactoring.
- Fine-grained control with @Bean + auto-detection.

COMMON INTERVIEW QUESTIONS + SHORT ANSWERS


Q1. Difference between XML config and Java-based config?
- XML uses <bean> tags; Java config uses @Configuration + @Bean.
- Java config is type-safe and easier to refactor.
Q2. What is the default bean scope in Spring?
- Singleton (only one object per Spring container).
Q3. When to use @Primary vs @Qualifier?
- @Primary → make one bean default.
- @Qualifier → explicitly choose one when multiple beans exist.
Q4. Types of Autowiring in annotations?
- Field, Constructor, Setter injection.
Q5. Difference between @Component and @Bean?
- @Component → class-level, auto-scanned.
- @Bean → method-level, manual bean definition.
Q6. Why use @Value?
- To inject constants or values from properties into fields.
Q7. Advantage of Java-based config? - Type-safe, no XML, IDE support, reusable.
========================================================
SPRING → SPRING BOOT + LAYERED ARCHITECTURE NOTES
========================================================
1) Moving from Spring to Spring Boot
- Spring (old way):
* Required lots of XML configuration.
* Manual setup of DispatcherServlet, DataSource, beans.
* Needed external Tomcat to deploy WAR files.
- Spring Boot (new way):
* Convention over configuration.
* Uses @SpringBootApplication (auto-configuration).
* Embedded Tomcat (no need to deploy WAR, just run jar).
* Starter dependencies (spring-boot-starter-web, spring-boot-starter-data-jpa, etc).
* Actuator for monitoring.
Q: Why Spring Boot?
A: Reduces boilerplate, faster development, production-ready.
2) Layered Architecture in Spring Boot
a) Controller Layer (Web Layer)
- Handles HTTP requests (GET, POST, PUT, DELETE).
- Uses @RestController / @Controller.
- Calls Service layer for business logic.
- Example: @GetMapping("/students")

b) Service Layer (Business Layer)


- Contains business logic.
- Uses @Service annotation.
- Calls Repository layer to interact with DB.
- Keeps Controller "thin" and clean.

c) Repository Layer (Data Access Layer)


- Interacts with database (CRUD operations).
- Uses @Repository annotation.
- Typically extends JpaRepository or CrudRepository.
- Hides complexity of JDBC/SQL from Service.

d) Model Layer (Entity Layer)


- Represents database tables as Java classes.
- Uses @Entity, @Id, @GeneratedValue.
3) How it Works (Flow)
Client (HTTP Request) → Controller → Service → Repository → Database
Database (Result) → Repository → Service → Controller → Client (HTTP Response)
4) Example Understanding
- Controller: Accept request "/addLaptop"
- Service: Check if laptop good for programming, then save.
- Repository: Insert into DB (save()).
- Client: Gets "Laptop saved successfully".

5) Benefits of Layered Architecture


- Separation of concerns (clean code).
- Easier testing (mocking service/repo).
- Reusability (same service used by multiple controllers).
- Scalability (each layer can grow independently).

6) Interview Questions & Answers


Q1: What is difference between @Controller and @RestController?
A1: @Controller → returns view (JSP/HTML).
@RestController → returns JSON/XML response (REST APIs).
Q2: Why use @Service annotation?
A2: Marks class as service, indicates business logic layer, helps with component scanning.
Q3: What is @Repository used for?
A3: It marks DAO classes, translates DB exceptions into Spring’s DataAccessException.
Q4: Can we call Repository directly from Controller?
A4: Yes, but not recommended. Service layer provides abstraction & business logic.
Q5: What is the role of Model/Entity layer?
A5: Represents DB tables as objects (ORM). Example: Student {id, name, marks}.
Q6: How does Spring Boot reduce boilerplate in repositories?
A6: By using Spring Data JPA → no need to write SQL queries for basic CRUD.
Q7: What is dependency injection in this context?
A7: Spring automatically injects (wires) beans like Service into Controller, Repository into Service.
=======================================================
SPRING JDBC + SPRING BOOT INTERVIEW NOTES
=======================================================
1) What is Spring JDBC?
- Spring JDBC simplifies database operations (insert, update, query).
- Uses JdbcTemplate for CRUD instead of writing boilerplate JDBC code.

Q: Why JdbcTemplate?
A: It handles resource management (connection, statement, result set)
and reduces boilerplate.

2) Important Annotations
@Component → Marks a class as Spring bean
@Scope → Defines bean scope (singleton, prototype, etc.)
@Repository → Data access layer, interacts with DB
@Service → Business logic layer
@Autowired → Dependency Injection
@SpringBootApplication → Entry point of Spring Boot app

3) Layered Architecture
Model (Entity) → Represents table (e.g., Student)
Repository → Handles SQL queries using JdbcTemplate
Service → Contains business logic
Main App → Runs the project, connects layers

4) Key Concepts
- JdbcTemplate: Main class to interact with DB.
- RowMapper: Maps ResultSet rows into Java objects.
- Dependency Injection: Spring auto-injects JdbcTemplate/beans using @Autowired.
- Datasource: Configured in [Link] for DB connection.
- Exception Handling: @Repository translates SQL exceptions into Spring’s DataAccessException.

5) Common Interview Questions


Q: What is JdbcTemplate?
A: A helper class that simplifies database access and handles resources automatically.

Q: Why use RowMapper in Spring JDBC?


A: To convert each row from ResultSet into a Java object.

Q: How does Spring Boot configure JdbcTemplate?


A: Spring Boot auto-configures JdbcTemplate if spring-boot-starter-jdbc is on classpath and
datasource is defined.

Q: What is the role of @Repository in JDBC?


A: Marks the class as DAO, provides exception translation.

Q: Difference between Statement, PreparedStatement, and JdbcTemplate?


A: Statement → plain SQL, risk of SQL injection
- PreparedStatement → precompiled SQL, safer, faster
- JdbcTemplate → wraps PreparedStatement, manages resources, reduces boilerplate
Q: Why use @Scope("prototype") on model beans?
A: Ensures a new object is created every time it is requested, useful for entities like Student.

Q: How does Dependency Injection work in Spring JDBC?


A: @Autowired injects JdbcTemplate into Repository and Repository into Service.

Q: How does Spring Boot reduce JDBC boilerplate?


A: Auto-configures DataSource & JdbcTemplate, no need for manual DriverManager or connection
handling.

========================================================

JDBC (Java Database Connectivity)


========================================================
1) Introduction
- JDBC is an API in Java used to connect and interact with databases.
- Full form: Java Database Connectivity.
- It provides a standard way to execute SQL queries using Java.
Steps (JDBC workflow):
1. Import the JDBC package.
2. Load & Register the driver ([Link]()) → older style.
3. Establish Connection ([Link]()).
4. Create Statement (Statement / PreparedStatement).
5. Execute SQL queries (execute, executeUpdate, executeQuery).
6. Process the ResultSet.
7. Close the connection.
=======================================================
SERVLET BASICS + TOMCAT NOTES (QUICK REVISION)
=======================================================

1) Web Application Introduction


-------------------------------
- WebApp = collection of servlets, JSP, HTML, CSS, JS.
- Runs on web servers (like Apache Tomcat).
- Needs deployment descriptor ([Link]) or annotations.

Q: What is a servlet?
A: A servlet is a Java class that handles HTTP requests and generates responses (usually HTML).

2) Creating a Servlet Project


- Create Maven/Gradle project.
- Add servlet dependency ([Link]-api).
- Write servlet by extending HttpServlet.
- Override doGet() / doPost().

Q: Why extend HttpServlet?


A: Because it provides default implementations for handling HTTP methods.

3) Running Tomcat Server


- Tomcat is a servlet container (implements Java Servlet spec).
- Can run:
a) Standalone (deploy WAR into Tomcat/webapps).
b) Embedded (use Tomcat API in Java main method).
- Port default = 8080.

Q: Difference between servlet container and web server?


A: Servlet container manages lifecycle of servlets, web server only serves static content.

4) Servlet Mapping
- Maps a URL pattern to a servlet.
- Can be done in:
a) [Link]
b) Annotation: @WebServlet("/hello")
c) Programmatically with Tomcat API

Example (programmatic):
[Link](context, "HelloServlet", new HelloServlet());
[Link]("/hello", "HelloServlet");

Q: What happens if 2 servlets mapped to same URL?


A: Tomcat throws conflict error at startup.
5) Responding to the Client

- Use HttpServletResponse object.


- [Link]("text/html");
- PrintWriter out = [Link]();
- [Link]("<h1>Hello World</h1>");

Q: Why call setContentType()?


A: To tell browser how to interpret response (html, json, xml, etc.).

6) Servlet Lifecycle (important for interviews)


a) init() → called once when servlet is created.
b) service() → called for every request, delegates to doGet/doPost.
c) destroy() → called before servlet is destroyed.

Q: Who creates and manages servlet lifecycle?


A: Servlet container (Tomcat).

7) Example Flow
1. Client sends request → [Link]
2. Tomcat receives request → finds mapped servlet.
3. Calls [Link]()
4. Servlet generates HTML response.
5. Tomcat sends response back to browser.

Q: What is DispatcherServlet in Spring vs normal Servlet?


A: DispatcherServlet is special front controller in Spring MVC.
Normal servlet directly handles requests.

8) Common Interview Questions

Q: Difference between doGet() and doPost()?


A: doGet → request data in URL, limited length, cached, idempotent.
doPost → request data in body, no length limit, secure for sensitive data.

Q: What is difference between forward() and sendRedirect()?


A: forward() → server-side, same request.
sendRedirect() → client-side, new request, URL changes.

Q: Can servlet handle both GET and POST?


A: Yes, by overriding both doGet() and doPost().

Q: What is content type application/json used for?


A: To tell browser the response is JSON, not HTML.
=======================================================
SPRING BOOT WEB MVC NOTES (QUICK REVISION)
=======================================================

1) Creating a Spring Boot Web Project


- Use Spring Initializr → choose Spring Web + DevTools.
- Auto-configures Tomcat as embedded server.
- Place JSP files in `/src/main/webapp/views/`.

Q: How is Spring Boot web project different from normal Spring MVC?
A: Spring Boot removes xml configs, uses starters, embedded server, and auto config.

2) MVC in Spring Boot


- M → Model (data / business object)
- V → View (JSP/Thymeleaf for UI)
- C → Controller (handles requests, returns model+view)

Q: Explain Spring MVC flow?


A: Request → DispatcherServlet → Controller → Service → Model → ViewResolver → JSP.

3) Creating JSP Page


- JSP files kept in `/webapp/views/`.
- Define prefix & suffix in `[Link]`:
[Link]=/views/
[Link]=.jsp

Q: Why prefix/suffix?
A: So controller only returns logical view name ("index"), Spring adds prefix+suffix to form path.

4) Creating Controller
- Annotate with `@Controller`.
- Use `@RequestMapping` to map URLs.
- Return view name (ex: "index").

Q: Difference between @Controller and @RestController?


A: @Controller returns views (JSP/HTML).
@RestController returns data (JSON/XML).

5) Request Mapping
- @RequestMapping maps URL → method.
- Can specify method type: @GetMapping, @PostMapping.

Q: What happens if two methods have same @RequestMapping?


A: Spring will throw "Ambiguous mapping" error.

6) Sending Data to Controller


3 common ways:
a) HttpServletRequest + HttpSession
b) @RequestParam("paramName") int num
c) Binding object using @ModelAttribute or directly as method param.
7) Accepting Data the Servlet Way
- HttpServletRequest req → getParameter("num1")
- HttpSession session → setAttribute("result", result)
- Old style (not preferred in Spring Boot).

8) Using RequestParam
- Cleaner than servlet way.
- Directly binds request params to method args.
Example: @RequestParam("num1") int num1

Q: Difference between @RequestParam and @PathVariable?


A: @RequestParam → extracts from query string (?id=1).
@PathVariable → extracts from URI (/user/1).

9) Model Object
- Used to pass data from Controller → View.
- [Link]("key", value).

Q: Why use Model instead of session?


A: Model is request-scoped, session is across requests. Model is cleaner for single request.

10) ModelAndView
- Combines model + view in one object.
- [Link]("key", value);
- [Link]("result");

Q: Difference between Model and ModelAndView?


A: Model → just data,
ModelAndView → data + view name together.

11) Need for @ModelAttribute


- Automatically binds form fields → object properties.
- Example: public String addAlien(@ModelAttribute Alien alien).
- Avoids manually setting fields one by one.

Q: When to use @ModelAttribute?


A: When binding whole form data into an object.

12) Displaying Data on JSP


- Use Expression Language (EL): ${result}, ${alien}.
- Can also use JSTL tags.
Q: Why prefer EL over scriptlets (<%= %>)?
A: EL is cleaner, more readable, and separates Java from JSP.
13) Common Interview Questions

Q: What is DispatcherServlet?
A: Front Controller in Spring MVC that handles all requests and dispatches to controllers.

Q: Difference between forward and redirect?


A: Forward → server-side, same request.
Redirect → client-side, new request (URL changes).

Q: How to pass global data to all views?


A: Use @ModelAttribute at method level in controller.

Q: Can JSP be used in Spring Boot?


A: Yes, but needs proper prefix/suffix config. Thymeleaf is more common in modern projects.

========================================================
JDBC (Java Database Connectivity)
========================================================
2) Connecting Java with DB
- Use Connection object.
- Example:
Connection con = [Link](url, user, pass);
- URL format differs by DB:
* MySQL → jdbc:mysql://localhost:3306/dbname
* SQL Server → jdbc:sqlserver://localhost:1433;databaseName=dbname
* Oracle → jdbc:oracle:thin:@localhost:1521:xe
3) Executing and Processing Queries
- Using Statement:
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM student");
- Processing:
while([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
}
4) Fetching All Records
- Use SELECT query with ResultSet.
- Iterate with while([Link]()).
- Can fetch by column index or column name.
5) CRUD Operations
- Create (INSERT)
- Read (SELECT)
- Update (UPDATE)
- Delete (DELETE)
- Example:
* INSERT → [Link]("insert into student values(1,'John',80)");
* SELECT → [Link]("select * from student");
* UPDATE → [Link]("update student set marks=90 where id=1");
* DELETE → [Link]("delete from student where id=1");

6) Problems with Statement


- Vulnerable to SQL Injection.
- Harder to reuse queries with parameters.
- Less efficient because SQL is compiled every time.
7) PreparedStatement
- Solves SQL Injection problem.
- Precompiled → faster for repeated execution.
- Allows placeholders (?) for parameters.
- Example:
String sql = "insert into student values (?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, 1);
[Link](2, "Ritesh");
[Link](3, 85);
[Link]();
8) Interview Questions & Answers
Q1: What is JDBC?
A1: JDBC is an API in Java that allows Java programs to interact with relational databases.
Q2: What are the steps in JDBC?
A2: Import package → Load driver → Create connection → Create statement → Execute query →
Process result → Close connection.
Q3: Difference between Statement and PreparedStatement?
A3:- Statement: Executes static SQL, prone to SQL Injection.
- PreparedStatement: Uses placeholders (?), prevents injection, precompiled → faster.
Q4: What are CRUD operations in JDBC?
A4: Create (Insert), Read (Select), Update, Delete.
Q5: What is ResultSet?
A5: It is an object that stores the result of a SELECT query and allows navigation through rows.
Q6: Can JDBC connect to any database?
A6: Yes, as long as the database vendor provides a JDBC driver.
Q7: What is SQL Injection and how to prevent it?
A7: SQL Injection is when malicious SQL is injected via user input.
Prevent using PreparedStatement instead of Statement.
Q8: What is the difference between execute(), executeUpdate(), and executeQuery()?
A8: - execute() → returns boolean (true if result is ResultSet).
- executeQuery() → used for SELECT, returns ResultSet.
- executeUpdate() → used for INSERT/UPDATE/DELETE, returns number of rows affected.
========================================================

MAVEN (Build Tool)


========================================================
1) Introduction
- Maven = Build automation & dependency management tool for Java.
- Uses **[Link]** (Project Object Model) to manage:
→ Build (compile, test, package, deploy)
→ Dependencies (JARs/libraries)
→ Plugins
2) Getting Dependencies
- No need to download JARs manually.
- Just add dependency in [Link] → Maven fetches it.
Example:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
- Default download → **Maven Central Repository**
3) Effective POM
- Final POM Maven uses after merging:
* Your [Link]
* Super POM (default)
* Parent POM (if any)
- Command: mvn help:effective-pom
4) Maven Archetype
- Archetype = Ready-made project template.
- Example:
mvn archetype:generate
- Common archetypes:
* quickstart → simple Java project
* webapp → web project
5) How Maven Works
Step 1: Write [Link]
Step 2: Run command (ex: mvn clean install)
Step 3: Maven downloads jars
Step 4: Compiles, tests, packages (jar/war)
Step 5: Saves jars in local repo → C:\Users\<user>\.m2\repository
6) Maven Repositories
- Local → .m2 folder on your PC
- Central → Public repo (default)
- Remote → Company/private repo
Website: [Link]
(Search any library → Copy dependency → Paste in [Link])

7) Interview Q&A
Q1: What is Maven?
A1: Build automation & dependency management tool.
Q2: What is [Link]?
A2: Config file with project info, dependencies, plugins.
Q3: What is Effective POM?
A3: Final POM = User POM + Super POM + Parent POM.
Q4: What is Archetype?
A4: Template for creating new projects.
Q5: How Maven handles dependencies?
A5: Checks Local repo → Central repo → Remote repo.
Q6: Local vs Central vs Remote repo?
A6: Local = PC, Central = Apache public repo, Remote = private repo.
Q7: [Link] use?
A7: To search dependencies (groupId, artifactId, version).
========================================================
SPRING MVC (Without Spring Boot)
========================================================

1) Introduction
- Spring MVC = Web framework on top of Servlet API.
- Follows MVC pattern:
* Model → Business logic / Data
* View → JSP / HTML (UI)
* Controller → Handles requests

- Without Spring Boot, we need to configure manually:


* [Link]
* DispatcherServlet
* [Link] (Spring config)
* View Resolver

2) Running on Tomcat in Eclipse


- Create Dynamic Web Project in Eclipse.
- Add Tomcat server.
- Add Spring JARs (or use Maven).
- Deploy project on Tomcat and run.

3) DispatcherServlet
- Acts as **Front Controller** in Spring MVC.
- Catches all requests and forwards to the correct controller.
- Defined in **[Link]**.
- DispatcherServlet looks for a config file named:
<servlet-name>-[Link] (e.g., [Link]).
4) [Link] (Spring Config File)
- Found inside WEB-INF.
- Defines:
* Component Scan → tells Spring where to search for controllers/beans.
* Annotation Config → enables @Controller, @Autowired, etc.
* View Resolver → maps logical names to JSP files.
Flow:
1. User request → DispatcherServlet intercepts.
2. [Link] tells Dispatcher which controllers exist.
3. Controller runs → returns a view name.
4. View Resolver adds prefix/suffix → loads JSP.
5. JSP is displayed.

5) InternalResourceViewResolver
- Removes need to write full JSP path in controller.
- Example: return "home" → resolves to /views/[Link].-

6) Example Request Flow


1. User → [Link]
2. DispatcherServlet catches request.
3. Finds correct controller (via component-scan).
4. Controller returns "index".
5. ViewResolver → maps "index" → /views/[Link].
6. JSP is shown as response.

7) Difference: Spring MVC vs Spring Boot


Spring MVC (without Boot):
- Manual setup ([Link], [Link], Tomcat).
- Need to add all dependencies (jars).
- Need external Tomcat server.
Spring Boot:
- Auto-configuration (no [Link]).
- Uses [Link] / annotations instead of [Link].
- Embedded Tomcat → run directly (no need to deploy manually).
- Starter dependencies simplify setup.
Simple Words:
- **Spring MVC** = “You configure everything yourself.”
- **Spring Boot** = “Spring configures everything for you.”

8) Interview Q&A
Q1: What is DispatcherServlet?
A1: It’s the Front Controller in Spring MVC that routes requests to controllers.
Q2: What is [Link] used for?
A2: It’s the Spring configuration file – defines component-scan, annotations, and view resolver.
Q3: Why do we use InternalResourceViewResolver?
A3: To map logical names returned by controllers into actual JSP paths.
Q4: What is the difference between Spring MVC and Spring Boot?
A4:- MVC: manual setup ([Link], [Link], Tomcat deployment).
Boot: auto setup (no XML, embedded Tomcat, starter dependencies).
Q5: What happens if [Link] is missing?
A5: DispatcherServlet won’t know about controllers or views → requests fail.
Q6: Can we have multiple DispatcherServlets?
A6: Yes, each can handle different URL patterns and have its own [Link].
Q7: How does Spring Boot replace [Link]?
A7: Boot uses auto-configuration + annotations + [Link] instead of XML files.
========================================================
JobApp Project Notes
========================================================

Project Name: JobApp


Technology Stack:

• Backend: Java, Spring Boot


• Frontend: JSP (JavaServer Pages)
• Build Tool: Maven
• Server: Embedded Tomcat
• Extras: Lombok, JSTL, Tomcat Jasper
Project Description:

• JobApp is a demo Spring Boot web application simulating a job portal/contact system.
• Users can navigate Home, Contact, and other pages.
• Clicking "Contact" can open Instagram or any external link.

How JobApp Works:


1. Spring Boot Application
- Runs on embedded Tomcat.
- @SpringBootApplication initializes the app.
2. Controllers
- Annotated with @Controller.
- Handles requests like /home → [Link], /contact → [Link].
3. Views (JSP)
- Stored in src/main/webapp/WEB-INF/views/
- Example: [Link], [Link]
- JSTL used for loops, conditions, and dynamic content.
4. Dependencies
- spring-boot-starter-web: REST APIs & web pages
- lombok: Reduces boilerplate code
- tomcat-jasper, [Link]-api: JSP compilation & JSTL support
5. Maven Build
- mvn clean install: Build project
- mvn spring-boot:run: Run project on [Link]
6. Contact Feature (Instagram)
- Example JSP button linking Instagram:
<a href="[Link] target="_blank">
<button>Instagram</button>
</a>
How to Make This Project (Step-by-Step):
1. Setup Maven project with Spring Boot parent (4.0.0-M2)
2. Add dependencies: Web, Lombok, JSP, JSTL, Tomcat Jasper
3. Create Controllers
Example:
@Controller
public class HomeController {
@GetMapping("/")
public String home() { return "index"; }
@GetMapping("/contact")
public String contact() { return "contact"; }
}
4. Create JSP pages ([Link], [Link])
5. Run Application
- Run [Link]
- Open browser: [Link]
6. Add Instagram Button in [Link] (as shown above)

Project Flow Diagram (Simplified):


User → Browser → Spring Boot Controller → JSP View → Display Page
Click Contact → Controller loads [Link] → Instagram button opens Instagram
Interview Questions & Answers:
A. Spring Boot / Java Basics:
1. What is Spring Boot?
- Simplifies creating standalone Spring apps with embedded servers.
2. What are Spring Boot starters?
- Predefined dependencies for quick setup (e.g., spring-boot-starter-web)
3. What is @SpringBootApplication?
- Combination of @Configuration, @EnableAutoConfiguration, @ComponentScan
4. What is Lombok?
- Reduces boilerplate code like getters, setters, constructors.

B. JSP / Frontend Questions:


1. Where are JSP files stored?
- src/main/webapp/WEB-INF/views/
2. What is JSTL?
- JavaServer Pages Standard Tag Library for loops, conditions, formatting
3. How to link button to Instagram?
- Use <a href="[Link]
target="_blank"><button>Instagram</button></a>

C. Maven / Build Questions:


1. What is Maven?
- Build automation tool; manages dependencies and builds project
2. Purpose of spring-boot-maven-plugin?
- Package Spring Boot apps as executable JAR/WAR
3. How to run project using Maven?
- mvn clean install → Build
- mvn spring-boot:run → Run
D. Common JobApp Questions:
1. Explain your project JobApp.
- Spring Boot + JSP app with Home and Contact pages, Contact links to Instagram
2. How does Contact page work?
- Controller returns [Link]; Instagram button opens in new tab
3. How to add new pages?
- Create JSP → Add controller method returning page name
4. MVC pattern?
- Controller handles request, Model stores data, View renders output
5. Error handling?
- Use @ControllerAdvice or try-catch in controllers
6. Deployment?
- Build WAR/JAR → Deploy on Tomcat or cloud
E. Additional Questions (Short & Simple Answers):
1. Difference between JSP vs Thymeleaf:
- JSP: Older, server-side, uses Java code in pages.
- Thymeleaf: Modern, natural templates, easier for HTML + Spring integration.

2. Using Bootstrap or CSS with JSP:


- Include CSS/Bootstrap in <head> using <link> tag.
- Use classes in HTML elements for styling.

3. How embedded Tomcat works:


- Spring Boot has built-in Tomcat server.
- Runs automatically when app starts, no need to install separately.

4. Explain annotations:
- @Controller → Marks class as Spring MVC controller.
- @GetMapping → Maps HTTP GET requests to a method.
- @SpringBootApplication → Main app annotation; combines @Configuration,
@EnableAutoConfiguration, @ComponentScan.

5. Adding database in future:


- Add dependency (Spring Data JPA + driver)
- Configure datasource in [Link]
- Create Entity, Repository, Service layers.
========================================================================
NOTES: REST API using Spring Boot
========================================================================

1. What is REST?
- REST = Representational State Transfer
- Standard way to build APIs
- Uses HTTP methods (GET, POST, PUT, DELETE)
- Data mostly in JSON format

2. HTTP Methods:
- GET → Read data (fetch all jobs / one job)
- POST → Create new data (add a job)
- PUT → Update existing data (update a job)
- DELETE → Remove data (delete a job)

3. RestController:
- @RestController used instead of @Controller
- Returns JSON data directly (no JSP)
- Example: JobRestController exposes REST endpoints

4. Using Postman:
- Test APIs without UI
- Select method (GET/POST/PUT/DELETE), enter URL
- For POST/PUT → send JSON body
- Example JSON:
{
"postId": 21,
"postProfile": "Cloud Architect",
"postDesc": "Design scalable cloud solutions",
"reqExperience": 5,
"postTechStack": ["AWS", "Azure", "Kubernetes"]
}

5. PathVariable:
- Used to pass values in URL
- Example: /jobPost/5 → getJob(5)

6. RequestBody:
- Maps JSON request body into Java object
- Example: @RequestBody JobPost jobPost

7. Content Negotiation:
- By default, Spring Boot REST APIs return JSON
- Can also return XML (if dependency is added)
- Handled automatically by Spring (based on request headers)

8. Connecting React and Spring:


- React (Frontend) calls Spring Boot REST APIs (Backend) using fetch() or axios
- Example: fetch("[Link] => [Link]())
9. Put and Delete Mapping:
- @PutMapping → Update job
- @DeleteMapping → Delete job

========================================================================
DIFFERENCE: Previous Topic (JSP MVC) vs Current Topic (REST API + React)
=======================================================================

Previous Project: JobApp (Spring Boot + JSP)


- Used @Controller
- Returned JSP pages (server-side rendering)
- UI handled inside Spring Boot (using JSP + Bootstrap/CSS)
- Contact feature linked Instagram
- Worked like a monolithic app (Backend + Frontend in one place)

Current Project: Spring Boot REST API + React UI


- Uses @RestController
- Returns JSON data (no JSP/HTML)
- Frontend (React) is completely separate project
- Backend = REST API only (Spring Boot), Frontend = React (UI)
- Communication happens via HTTP calls (fetch/axios)
- Easier for scaling → Backend and Frontend independent

========================================================================
Interview Questions (Short + Easy to Remember)
========================================================================

Q1. What is REST?


A. Style to build APIs using HTTP methods (GET, POST, PUT, DELETE), data in JSON.

Q2. Why use @RestController instead of @Controller?


A. @RestController returns JSON directly, no need for JSP/HTML.

Q3. How to test REST APIs?


A. Use Postman → select method, enter URL, send request (with JSON if needed).

Q4. Difference between @PathVariable and @RequestBody?


A. @PathVariable → value from URL
@RequestBody → value from request JSON

Q5. How do React and Spring communicate?


A. React sends HTTP requests (fetch/axios) to Spring Boot APIs, gets JSON response.

Q6. What is Content Negotiation?


A. Process of deciding response type (JSON/XML) based on client request.

Q7. Example of using PUT vs POST?


A. POST → Add new job
PUT → Update existing job
Q8. Why do we separate Service and Repository layers?
A. Service = Business logic
Repository = Data storage
→ Better code organization, easy to maintain.

===========================================================
NOTES: React UI ko Spring Boot ke saath Connect Karna
===========================================================

Starting Point:
- Mere paas React UI folder (GitHub se clone kiya) tha
- Backend project Spring Boot mein bana hua tha (REST APIs ready)
- Dono alag ports pe run hote hain:
React → [Link]
Spring Boot → [Link]

Problems Aayi:
1) Axios error: "Network Error"
→ Kyunki React aur Spring alag ports pe hain (CORS/Proxy issue)
2) Babel error (MUI ke karan)
→ Fix karne ke liye ek extra plugin install karna pada

Solutions / Changes Kiye:


1) React mein proxy setup:
[Link] mein add kiya:
"proxy": "[Link]

2) Babel error fix:


npm install --save-dev @babel/plugin-proposal-private-property-in-object

3) Contact Us mein Instagram link:


React Contact component mein code add kiya:
<a href="[Link]
target="_blank"
rel="noopener noreferrer">
Contact on Instagram
</a>

Testing Kiya:
- Browser pe [Link] → JSON data aaya
- React app run kiya → Axios ne data fetch kar liya
- Contact Us click karne pe Instagram profile open ho gaya

Summary (Simple Bhasha Mein):


- Spring Boot ke REST API ko React se connect kar diya
- Proxy add karke React aur Spring integrate kiya
- Babel ka error npm install se fix kiya
- Instagram link Contact page pe add kiya
===========================================================
INTERVIEW Q&A (React + Spring Boot Project)
===========================================================
Q1: How did you connect React with Spring Boot?

• Ans: Spring Boot gives REST APIs (port 8080).


• React runs on port 3000 and calls backend using Axios.
• Added proxy in React so requests go to backend.
Q2: How did you fix Axios "Network Error"?

• Ans: In [Link] added:


• "proxy": "[Link]
• This forwards React requests to backend.
Q3: How does Contact Us button open Instagram?

• Ans: In React component used <a> tag with my Instagram link.


• Added target="_blank" so it opens in new tab.
Q4: How did you fix Babel / MUI error?

• Ans: Installed extra plugin:


• npm install --save-dev @babel/plugin-proposal-private-property-in-object
Q5: If database is added in future, how will you do it?

• Ans: Use Spring Boot + JPA + MySQL (or MongoDB).


• Then JobPost data will come from DB instead of hardcoding.
Q6: What is the difference between JSP and React?
- JSP: server-side rendering (HTML created on backend).
- React: client-side rendering (fetch data using API).
Q7: What is the project stack?
- Frontend: React, Axios, Material UI
- Backend: Spring Boot, REST API
- Tools: Maven (backend), npm (frontend)
Q8: How does embedded Tomcat work?
- Spring Boot has built-in Tomcat.
- So no need to install Tomcat separately.
- Just run: mvn spring-boot:run
Q9: What was your role in this project?
- Built Spring Boot backend (JobPost APIs).
- Connected React frontend with backend.
- Added Contact feature (Instagram link).
Q10: If interviewer asks to run project, what will you do?

• Steps to run project: Run backend (Spring Boot on port 8080) → Run frontend (npm start
on port 3000) → Open React app, it shows data from backend.
========================================================================
NOTES: JPA DATA API using Spring Boot
========================================================================
1. Introduction:

• Spring Data JPA simplifies database operations in Spring Boot.


• It uses ORM (Object Relational Mapping) to map Java objects to database tables.
• JPA (Java Persistence API) is the specification, Spring Data JPA provides implementation.
2. Entity Creation:

• Use @Entity annotation to mark a class as a database table.


• Use @Id for primary key.
• Define fields as table columns.
• Example: Student class with RollNo, name, marks.
3. Repository:
- Use JpaRepository interface for CRUD operations.
- No need to write SQL manually for basic operations.
- Example methods:

• findAll() → get all records


• findById(id) → get record by id
• save(entity) → insert or update record
• delete(entity) → delete record
Custom queries using method naming:

• findByName(name)
• findByMarks(marks)
• findByMarksGreaterThan(marks)
4. Application Workflow:

• Create ApplicationContext using [Link]().


• Get beans for Entity and Repository.
• Set data in Entity objects.
• Save, update, delete, or fetch data using Repository methods.
5. Insert Data:
- Create entity objects and set values.
- [Link](entity) → inserts data in table.
6. Fetch Data:

• [Link]() → returns all records.


• [Link](id) → returns record by id.
• [Link]("name") → returns records matching name.
• [Link](value) → filter by condition.
7. Update Data:
- Set new values in existing entity object.
- [Link](entity) → updates record if primary key exists.
8. Delete Data:
- [Link](entity) → deletes record from table.
9. Search / Query DSL:
- Use method naming conventions in Repository to create queries.
- Example: findByMarksGreaterThan, findByName, etc.
10. JPA in JobApp Project:
- Could use similar pattern for storing JobPost entities in database.
- Mapping JobPost fields to table columns.
- Use JobRepo as JpaRepository.
11. Loading Data and Entities:
- Entities can be loaded via [Link]() or [Link]().
- Optional is used to handle null results safely.

Notes for Interview with Solutions:


1. Explain ORM and JPA:
- ORM (Object Relational Mapping) maps Java objects to database tables.
- JPA (Java Persistence API) is the specification for ORM in Java.
- Spring Data JPA implements JPA to simplify DB operations.
2. Example of saving an entity:

• Student s = new Student();


• [Link](101);
• [Link]("Navin");
• [Link](75);
• [Link](s); // Saves record in DB
3. Example of fetching entities:

• [Link](); // Returns all students


• [Link](101); // Returns student with RollNo 101
• [Link]("Navin"); // Returns list of students with name Navin
• [Link](70); // Returns students with marks > 70
4. Example of updating an entity:

• [Link](80); // change marks


• [Link](s); // Updates record because RollNo exists
5. Example of deleting an entity:
[Link](s); // Deletes student record from DB
6. Custom queries using method naming:
- findByName(name), findByMarks(marks), findByMarksGreaterThan(value)
- No need to write SQL manually
7. Difference between previous topic (Spring Boot + REST) and JPA:
- REST:

• Handles frontend-backend communication.


• Returns data via HTTP methods (GET, POST, PUT, DELETE).
• Example: JobRestController returns jobs to React UI.
- JPA:

• Handles database operations and storage.


• Manages entities (tables) directly in DB.
• Example: Student entity saved, fetched, updated, deleted via JpaRepository.

Spring Data JPA Notes


1. What is JPA?
- JPA = Java Persistence API
- Standard API in Java for ORM (Object-Relational Mapping)
- Maps Java objects (Entities) to database tables
2. What is ORM?
- ORM = Object-Relational Mapping
- Lets you work with Java objects instead of writing SQL
- Converts objects to table rows and vice versa
3. How JPA works behind the scenes:
- You define an Entity class (@Entity)
- JPA uses Hibernate (or any provider) to handle DB operations
- When you call [Link](entity):

• Checks if object exists → if yes, UPDATE; else INSERT


• Converts object fields to table columns
- [Link](id) → Generates SELECT query automatically
- [Link](id) → Generates DELETE query automatically
- [Link]() → Generates SELECT * query
- Supports custom queries via method names or @Query.
4. Common annotations:
- @Entity → marks class as a database entity
- @Id → primary key
- @GeneratedValue → auto-generate IDs
- @Column → map field to table column (optional)
- @Repository → marks repository layer
- @Service → marks service layer for business logic
5. Advantages / Uses of JPA:
- No manual SQL for CRUD operations
- Works with multiple databases
- Simplifies data access code
- Supports advanced queries (method names, JPQL, native SQL)
- Reduces boilerplate code
- Easy to maintain and scalable
6. How to use JPA in Spring Boot:
- Add dependency: spring-boot-starter-data-jpa
- Configure database in [Link]

• [Link]=jdbc:mysql://localhost:3306/dbname
• [Link]=root
• [Link]=root
• [Link]-auto=update
- Create Entity class
- Create Repository interface extending JpaRepository
- Inject repository in Service
- Perform CRUD via repo methods
7. Real project example:
- JobApp / JobPost:
* JobPost is @Entity
* JobRepo extends JpaRepository<JobPost, Integer>
* Service calls [Link](), [Link](), [Link]()
* Search by keyword: [Link]()
Interview Questions & Answers – React UI + Spring Boot + JPA Data
(Search, Update, Delete)
1. Cross-Origin Setup:
- @CrossOrigin(origins = "[Link] is added in JobRestController.
- Allows React frontend (port 3000) to call Spring Boot backend (port 8080).
2. Update Functionality:
- PUT mapping updated to accept PathVariable:
@PutMapping("jobPost/{postId}")
public JobPost updateJob(@PathVariable int postId, @RequestBody JobPost jobPost)
- Ensures the correct job is updated by setting [Link](postId)
- Frontend sends updated job details as JSON, backend updates DB using [Link](jobPost)
3. Delete Functionality:

• DELETE mapping with PathVariable:


• @DeleteMapping("jobPost/{postId}")
- public String deleteJob(@PathVariable int postId)
- Frontend calls this endpoint, backend deletes the job by ID using [Link](postId)
4. Search Functionality:
- GET mapping with keyword:
- @GetMapping("jobPosts/keyword/{keyword}")
- public List<JobPost> searchByKeyword(@PathVariable("keyword") String keyword)
- Backend calls [Link](keyword) → uses JPA query:
- [Link](keyword, keyword)
- Frontend sends keyword as input, backend returns matching jobs (profile or description contains
keyword)
5. Load Sample Data:
- GET mapping: @GetMapping("load")
- Pre-loads jobs into database using [Link](jobs)
- Useful for testing frontend search/update/delete without manual DB insertion
6. JPA Repository Methods Used:
- findAll() → fetch all jobs
- findById(id) → fetch specific job
- save(entity) → add or update job
- deleteById(id) → delete job
- findByPostProfileContainingOrPostDescContaining(keyword, keyword) → search jobs by
keyword
7. React UI Integration:
- React app calls backend endpoints via Axios:
• GET /jobPosts → show all jobs
• PUT /jobPost/{id} → update job
• DELETE /jobPost/{id} → delete job
• GET /jobPosts/keyword/{keyword} → search jobs
- Components: Table/List for jobs, Search input box, Update form, Delete button

8. Key Points for Interview:


- Explain how React communicates with Spring Boot backend:

• Uses Axios or fetch to send HTTP requests (GET, POST, PUT, DELETE).
• React updates the UI based on responses from backend.
- Search example:

• User types a keyword in React search box.


• Axios GET /jobPosts/keyword/{keyword} is called.
• Backend filters jobs using JPA ([Link]).
• React component updates state → shows filtered jobs.
- Update/Delete example:

• Click Update button → Axios PUT /jobPost/{id} → backend updates DB record.


• Click Delete button → Axios DELETE /jobPost/{id} → backend deletes record.
• React updates the displayed list after backend response.
- Difference with previous Spring Boot REST topic:

• Previous: Basic CRUD endpoints using dummy ArrayList.


• New: Full integration with JPA database, dynamic search, update/delete by ID, connected
React frontend.
9. Q: New JPA methods used here:

• [Link](entity) → add/update
• [Link](id) → delete
• [Link](id) → get by id
• [Link](keyword, keyword) → search
10. Q: How does search show results in React?
- User types keyword → Axios GET /jobPosts/keyword/{keyword}.
- React updates component state → table/list shows filtered jobs.
Notes: Spring Data REST in JobApp
1. Introduction:
- Spring Data REST automatically creates REST APIs for repositories.
- No need to write Controller or Service layer.
- With dependency spring-boot-starter-data-rest, all JpaRepository methods become endpoints.

2. Running the project:


- Run Spring Boot application.
- Default port: 8080
- Example endpoints:
* GET [Link] → list all jobs
* GET [Link] → get job by id
* POST [Link] → add new job
* PUT [Link] → update job
* DELETE [Link] → delete job

3. Update:
- Send PUT request to /jobRepos/{id} with updated JSON body.
- Spring Data REST finds the job by id and updates record in DB.
- Works internally by calling [Link]().

4. Delete:
- Send DELETE request to /jobRepos/{id}.
- Spring Data REST deletes record directly from DB.
- Works internally by calling [Link]().

5. How this JobApp works:


- Only two codes required:
* Entity class ([Link])
* Repository interface ([Link])
- Spring Data REST auto-generates CRUD APIs from JobRepo.
- No Controller/Service code needed → faster development.

Interview Questions & Answers (Spring Data REST):


1. Q: What is Spring Data REST?
A: A module that exposes Spring Data repositories as RESTful APIs automatically.

2. Q: How is it different from normal Spring Boot REST?


A: In Spring Boot REST we write Controller + Service manually.
In Spring Data REST, only Entity + Repository is enough.

3. Q: How do you update a job using Spring Data REST?


A: Send a PUT request to /jobRepos/{id} with updated JSON → handled by [Link]() internally.

4. Q: How do you delete a job?


A: Send a DELETE request to /jobRepos/{id} → handled by [Link]() internally.
5. Q: What are the advantages of Spring Data REST?
- Rapid API development.
- Reduces boilerplate code (no controller/service).
- Automatically follows REST/HATEOAS standards.

6. Q: Any disadvantages?
- Limited flexibility for custom logic.
- For complex APIs, normal REST controller is better.

7. Q: Difference between this topic and previous JPA topic?


- Previous (Spring Data JPA): We wrote Service + Controller + custom queries.
- Now (Spring Data REST): APIs are auto-generated, no extra layers needed.

Notes – Spring Data REST Output Explanation

1. Why output looks different?


- Spring Data REST does not return plain JSON arrays.
- It follows **HAL (Hypertext Application Language)** format.
- That’s why we see extra fields like `_embedded` and `_links`.

2. `_embedded`:
- Holds the actual data (entities).
- Inside it, we see the repository name → e.g., `jobRepos`.

3. `_links`:
- Provides navigation URLs (HATEOAS).
- Each record has its own "self" link → shows the direct URL to that object.

4. Purpose of HAL format:


- Makes APIs **self-descriptive** → client knows how to fetch more data.
- Supports **HATEOAS principle** (Hypermedia as the Engine of Application State).
- Easy navigation between collection (all jobs) and single resource (one job).

5. Example GET request:


- Request: GET /jobRepos
- Output:
{
"_embedded": {
"jobRepos": [
{ "postId": 101, "postProfile": "Software Engineer", ... ,
"_links": { "self": {"href": ".../jobRepos/101"} }
}
]
}}

6. Simple Meaning:
• embedded → Where your *data lives*.
• links → URLs to access or navigate to each resource.
• if HATEOAS is disabled → output becomes a plain JSON array without embedded and
links.
• By default Spring Data REST enables HATEOAS for hypermedia-driven APIs.
Notes – Spring AOP (Aspect Oriented Programming)
1. Introduction to AOP:
• AOP = Aspect Oriented Programming.
• Used to add cross-cutting concerns (logging, validation, performance monitoring)
without mixing them into business logic.
Interview Q: What is Spring AOP and why is it used?

A: AOP helps separate cross-cutting concerns (like logging, validation, performance monitoring)
from main business logic, keeping code clean and maintainable.

2. AOP Concepts:
• Aspect → Class with cross-cutting code (e.g., LoggingAspect).
• JoinPoint → Point during execution (method call, constructor call, etc.).
• Advice → Action taken at a JoinPoint (Before, After, Around).
• Pointcut → Expression to match JoinPoints (e.g., methods in JobService).

Interview Q: What is a JoinPoint?

A: It’s a point during execution, such as a method call, where advice can be applied.

3. Logging the Calls (Using LoggingAspect):


• @Before → runs before method (logs method call).
• @After → runs after method (logs execution).
• @AfterReturning → runs after success (logs success).
• @AfterThrowing → runs after exception (logs error).

✔ Example: If getJob() is called → logs call, success, or error.

Interview Q: How did you use AOP for logging in your project?

A: By creating a LoggingAspect with @Before, @After, @AfterReturning, and


@AfterThrowin to log method calls, execution, success, and errors in JobService.

4. Before Advice:
- Executes before target method.
- Example: @Before("execution(* [Link]*(..))") → logs before getJob().

Interview Q: What is Before Advice?

A: It executes before the actual method and is often used for logging, authentication, etc.

5. After Advice:
- Executes after target method (success or failure).
- Example: @After("execution(* [Link]*(..))").

Interview Q: When is After Advice executed?

A: It runs after a method finishes execution, whether successful or not.


6. Performance Monitoring (Using Around Advice):
• @Around → wraps the method call.
• Measures execution time → logs "Time taken by method".
• Example: monitorTime() → prints duration of JobService methods.

Interview Q: How did you measure performance using AOP?

A: By using @Around advice in PerformanceMonitorAspect, calculating time before & after


method execution, and logging duration.
7. Validating Input (Using Around Advice):
- @Around with args(postId).
- Checks if postId < 0 → makes it positive.
- Example: If input is -101 → updated to 101 before method runs.

Interview Q: How did you implement input validation using AOP?

A: Using ValidationAspect with @Around advice, which checks if postId is negative and

corrects it before calling [Link]().

8. Benefits of AOP:
• Clean separation of concerns.
• No need to add logging/validation code inside every service.
• Improves maintainability and readability.
Interview Q: What are the benefits of using AOP in Spring Boot projects?

A: It provides centralized logging, validation, performance monitoring, avoids code duplication,


and makes the project easier to maintain.
9. Key Concepts in AOP (with Real-Life Example)
a) Aspect
- The class where cross-cutting logic is written.
- Example: A "Security Guard" at a building. Guard = Aspect.
b) Advice
- The actual action taken (before, after, around method).
- Example: Guard checks ID card (Advice).
Types of Advice:
• @Before → Run before method.
Example: Log "Method started".
• @After → Run after method (always).
Example: Log "Method finished".
• @AfterReturning → Run if method succeeds.
Example: Print "Payment successful".
• @AfterThrowing → Run if method fails.
Example: Print "Error in transaction".
• @Around → Surrounds method call, can run before & after.
Example: Stopwatch around a race → start & stop time.
c) JoinPoint
- The point in program execution where advice can be applied.
- Example: A "method call". Like [Link]().
d) Pointcut
- The condition/expression to select which JoinPoints to apply.
- Example: Apply only to methods starting with "get".
e) Target Object
- The actual object whose method is being called.
- Example: JobService bean.
f) Proxy
- The object created by Spring AOP that wraps the target and applies advice.
- Example: A "middleman" that checks rules before giving access.
g) Weaving
- Process of linking aspects with target objects.
- Example: Stitching extra security system into a building.
10. Real-Life Analogy
Imagine a **Bank ATM**:

• Aspect → CCTV monitoring system.


• Advice → Recording starts before transaction, stops after.
• JoinPoint → "Withdraw money" operation.
• Pointcut → Apply advice only on "Cash Withdraw" (not balance check).
• Target Object → ATM machine.
• Proxy → Security software that connects user → ATM → CCTV.
• Weaving → Integrating CCTV logic with ATM machine.

11. Example in Code (From Project)

• LoggingAspect (@Before + @After + @AfterThrowing + @AfterReturning)


→ Logs method call, success, or failure.
• PerformanceMonitorAspect (@Around)
→ Measures execution time for JobService methods.
• ValidationAspect (@Around with args)
→ Checks input (postId), if negative converts to positive.

12. Why AOP is Powerful?


• No code duplication.
• Clean business logic (no logging/validation inside service).
• Easy to add/remove cross-cutting concerns.
• Centralized control.
Interview Questions & Answers
Q2: Difference between Advice and Pointcut?
- Advice = Action (what to do).
- Pointcut = Where to apply it (which methods).
Q3: What is a JoinPoint in Spring AOP?
A3: Any method execution where an advice can be applied.
Q4: How is @Around different from @Before and @After?
A4: @Around surrounds the method call → can run before, after, or even skip execution.
@Before/@After run only at specific points.
Q5: Where did you use AOP in your project?

• LoggingAspect for method calls.


• PerformanceMonitorAspect for monitoring time.
• ValidationAspect for fixing negative IDs.
Q6: How does Spring AOP work internally?

• Spring creates a proxy object.


• Proxy intercepts method calls.
• Executes advice (logging/validation).
• Then calls the actual method.
Q7. How does AOP work? (Step by Step)
- Spring creates a **proxy** around the service class.
- When a method is called, the proxy:
1. Checks if any **Advice** applies (@Before, @After, @Around).
2. Executes advice (like logging).
3. Runs the actual method (business logic).
4. Runs any post-execution advice (like performance monitor)
Example: Calling getJob(-101) →
• ValidationAspect changes ID to positive.
• LoggingAspect logs method call.
• PerformanceMonitorAspect calculates time taken.
• Then actual [Link]() runs.
SPRING SECURITY
1. What is Spring Security?

• Framework in Spring ecosystem.


• Provides authentication (who are you?) + authorization (what can you do?).
• Protects APIs and web apps from common attacks.
• Easily integrates with Spring Boot projects.

Interview Q:

Q: What is difference between authentication and authorization?


A: Authentication = verify identity (login), Authorization = check access (roles/permissions).
2. Importance of Security

• Prevents unauthorized users from accessing private data.


• Protects passwords, credit cards, personal info.
• Builds trust in application (users feel safe).
• Avoids legal + financial issues (data breach fines).
3. OWASP TOP 10 (most common attacks)
a. Injection (SQL, NoSQL, OS commands)
b. Broken Authentication (weak login)
c. Sensitive Data Exposure (unencrypted passwords)
d. XML External Entities (XXE)
e. Broken Access Control (user can access admin data)
f. Security Misconfiguration (default passwords, open ports)
g. Cross-Site Scripting (XSS)
h. Insecure Deserialization
i. Using Components with Vulnerabilities
j. Insufficient Logging & Monitoring

Interview Q:

Q: Name few OWASP Top 10 issues you faced in projects?


A: CSRF, SQL Injection, XSS are common. We use Spring Security filters and parameter binding to
prevent them.
4. Creating Spring Security Project

• Add spring-boot-starter-security dependency.


• Spring automatically creates a default login page.
• Default user credentials are generated (printed in console).
5. Spring Security Filters
Every request passes through a "filter chain". And - Order of filters matters.
Examples:
UsernamePasswordAuthenticationFilter – handles login
CsrfFilter – protects from CSRF attacks
BasicAuthenticationFilter – reads Basic Auth headers
Interview Q:

Q: Difference between Filter and Interceptor?


A: Filter is servlet-based, runs before request reaches servlet. Interceptor is Spring-specific, runs
inside Spring context.
6. Session ID

• When user logs in, server generates unique session ID.


• Stored in cookie, used to identify user across requests.
• Prevents repeated login.
7. Setting Username and Password

• [Link]:
[Link]=admin
[Link]=admin123
• Good for quick testing, but not for production.
8. Basic Auth using Postman

• Select "Authorization → Basic Auth".


• Enter username + password.
• Postman adds "Authorization: Basic <token>" in header.
9. What is CSRF (Cross-Site Request Forgery)?

• Attack where attacker tricks a logged-in user into performing unwanted action.
• Example: if user is logged in to [Link], attacker sends a fake request to transfer money.
10. Error without CSRF token
- Spring Security rejects POST/PUT/DELETE without CSRF token.
- Error: 403 Forbidden.
11. Sending CSRF token

• Token is included in hidden form fields or request headers.


• Server checks if token matches → prevents CSRF.
12. SameSite Strict

• Cookie attribute that prevents cookies from being sent with cross-site requests.
• Protects against CSRF.
13. Security Configuration
- Using SecurityFilterChain, we define:
Which URLs are public
Which need login
Which need roles (USER/ADMIN)

14. Disabling CSRF token


- For APIs and Postman testing:
[Link]().disable();
- But in real production → CSRF should be enabled.
15. Getting ready for Users Database

• Instead of hardcoding users, store in DB (MySQL, PostgreSQL, etc).


• Users table: id, username, password, role.
16. Working with Multiple Users

• Example: one USER, one ADMIN.


• Role decides access → @PreAuthorize("hasRole('ADMIN')").
17. AuthenticationProvider

• Validates credentials.
• DaoAuthenticationProvider = works with DB + UserDetailsService.
18. Creating User Table and DB properties

• Table columns: id, username, password, role


• [Link] → DB config
• Spring JPA manages queries.
19. UserDetailsService + User Repository

• UserDetailsService: loads user by username.


• UserRepo: JpaRepository for User entity.
20. UserDetails and UserPrincipal

• UserDetails: Spring Security interface.


• UserPrincipal: our wrapper around User (to connect DB user with Spring Security).
21. What is BCrypt?

• Strong hashing algorithm for passwords.


• One-way encryption → cannot be reversed.
• Adds salt → prevents rainbow table attacks.

Interview Q:

Q: Why not store plain text passwords?


A: Plain text can be stolen → users compromised. Always hash with BCrypt.
22. User Registration

• POST API: /users/register


• Accepts username + password + role
• Encodes password with BCrypt
• Saves to DB
23. BCrypt encoding for User Registration

• Before saving password → [Link](rawPassword)


• Stored password looks like: $2a$12$....
24. Setting Password Encoder

• @Bean → BCryptPasswordEncoder
• Used in AuthenticationProvider
• Matches entered password with stored hash

PROJECT WORKFLOW (Step by Step)


1) User sends request → API endpoint
2) Request passes through Spring Security Filter Chain
3) AuthenticationProvider checks credentials

• If using DB → loadUserByUsername()
• Compare entered password with BCrypt hash
4) If valid → Authentication object created, user is logged in
5) Authorization step → Check user role

• Example: ADMIN can access /users/all


• USER can only access /profile
6) If allowed → controller executes
7) If not allowed → 403 Forbidden
8) For new users → registration API hashes password + saves to DB
9) For update/delete → secured with roles

Common Interview Questions:


Q1: What is difference between @PreAuthorize and @Secured?
A: Both are for method-level security. @PreAuthorize uses SpEL (flexible), @Secured is simple role-
based.
Q2: Why do we use @Transactional in update methods?
A: So changes are auto-saved without calling save() explicitly. It manages DB transaction.
Q3: How does BCrypt work?
A: It adds salt and hashes password multiple times. Each hash is unique even for same password.
Q4: Can we disable default login form?
A: Yes, by customizing HttpSecurity config and defining our own login page.
Q5: What is stateless vs stateful session?
A: Stateful = server stores session (cookie + session ID). Stateless = no session, every request must
have credentials (used in APIs).
SPRING SECURITY – IMPORTANT ANNOTATIONS
1. @EnableWebSecurity

• Enables Spring Security in project.


• Usually placed on configuration class.

Interview Q:

Q: Is @EnableWebSecurity mandatory?
A: Since Spring Boot 3, not mandatory (auto enabled),
but we use it for custom configuration.
2. @EnableMethodSecurity

• Enables method-level security.


• Allows @PreAuthorize, @PostAuthorize, @Secured, @RolesAllowed.
• Replaces older @EnableGlobalMethodSecurity.
3. @PreAuthorize("condition")

• Runs before method execution.


• Checks role/authority/condition.
• Example:
@PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers();

Interview Q:

Q: Difference between hasRole and hasAuthority?

• hasRole("ADMIN") = checks for "ROLE_ADMIN".


• hasAuthority("ADMIN") = checks for "ADMIN" directly.
• (Spring automatically prefixes "ROLE_")
4. @PostAuthorize("condition")

• Runs after method execution.


• Can validate return data.
• Example:
@PostAuthorize("[Link] == [Link]")
public User getUser();
5. @Secured({"ROLE_ADMIN", "ROLE_MANAGER"})

• Older annotation for role-based access.


• Simpler but less flexible.
• Only checks roles, not conditions.
6. @RolesAllowed({"ROLE_USER"})

• Comes from JSR-250.


• Similar to @Secured, works with roles.
• Needs @EnableMethodSecurity(jsr250Enabled = true).
7. @WithMockUser

• Used in testing.
• Mocks a logged-in user with username/role.
• Example:
@Test
@WithMockUser(username="admin", roles={"ADMIN"})
void testGetUsers() { ... }
8. @AuthenticationPrincipal
- Injects current logged-in user’s principal object.
- Example:
public String profile(@AuthenticationPrincipal UserDetails user) {
return "Hello " + [Link]();
}
9. @PermitAll

• Allows access to everyone (no authentication required).


• Comes from JSR-250.
• Needs jsr250Enabled = true in config.
10. @DenyAll

• Blocks access for everyone.


• Also JSR-250 annotation.
11. @CrossOrigin
- Used for CORS (Cross-Origin Resource Sharing).
- Example:
@CrossOrigin(origins = "[Link]
public List<User> getAllUsers();

Quick Recap Table


• @EnableWebSecurity → enables Spring Security
• @EnableMethodSecurity → enables method-level security
• @PreAuthorize → check before method
• @PostAuthorize → check after method
• @Secured → role-based access
• @RolesAllowed → role-based (JSR-250)
• @WithMockUser → for testing
• @AuthenticationPrincipal → get current user
• @PermitAll / @DenyAll → allow/block all
Common Interview Questions
Q1: Which is better – @PreAuthorize or @Secured?

• @PreAuthorize is better, supports SpEL (conditions).


• @Secured only supports simple role checks.
Q2: Can we use multiple annotations together?
A: Yes, but it’s better to stick with one style for consistency.
Q3: How does @AuthenticationPrincipal differ from SecurityContextHolder?

• Both give current user info.


• @AuthenticationPrincipal injects automatically into method params.
• SecurityContextHolder requires manual code.
Q4: What is the difference between @RolesAllowed and @Secured?

• @RolesAllowed = JSR-250 standard, portable.


• @Secured = Spring-specific.

Q5: Which annotation would you use to check if the logged-in user is the same as the resources
Owner ?

• @PreAuthorize or @PostAuthorize with SpEL expression.


• Example: @PreAuthorize("#id == [Link]")
Spring Security + JWT – Complete Notes
1. Encryption & Decryption

• Encryption → lock data (convert to unreadable text)


• Decryption → unlock data (get back original)
• Example: Password saved in DB should be encrypted
2. Digital Signature

• Like signing a paper but in digital form


• Ensures → data is not changed + sender is authentic
• Used in JWT (signing tokens with secret key)
3. Why JWT?

• Sessionless authentication (no server memory used)


• Portable → can be used across services (Microservices)
• Faster → no DB call needed on every request
• Secure → signed with secret key
4. What is JWT?
JSON Web Token → small string with 3 parts

• Header (type + algorithm)


• Payload (data like username, role)
• Signature (secret key used)

5. Custom Login
- Instead of default Spring login form
- Create a login API → verify user with DB
- If success → generate JWT token
6. Generate Token
- When user logs in successfully
- Server creates JWT token with username + expiry + signature
7. Token Generated
- Sent back to client (Postman / React app)
- Client stores token (localStorage / sessionStorage / memory)
8. Creating a JWT Filter
- Every request is intercepted by JwtFilter
- Steps:
• Check "Authorization" header
• Extract JWT token
• Validate token with secret key
• If valid → load user details and set in SecurityContext
9. Setting Auth Token in Security Context

• SecurityContextHolder holds login info


• If token is valid → create Authentication object
• Now Spring knows → request is authenticated
10. Validating Token
- Check if:
✓ Signature is correct
✓ Token is not expired
✓ Token username matches DB user
- If valid → allow request
- If invalid → reject with 403
11. JWT Summary (easy words)
✓ Login → Generate token → Send to client
✓ Client → Send token in every request
✓ Server → Validate token in filter
✓ If ok → request passes, else → 403 error
✓ No session needed, fully stateless

Interview Questions (with short answers)

Q1: Why do we use JWT instead of Session?


- JWT is stateless, scalable, and doesn’t store session in server.
Q2: What are JWT parts?
- Header, Payload, Signature
Q3: How is JWT secured?
- Signed with secret key (HS256/RS256)
- Can’t be modified without breaking signature
Q4: Where do we store JWT in frontend?
- LocalStorage, SessionStorage, or HttpOnly cookies
Q5: What if JWT is stolen?
- Attacker can use it → solution: short expiry + refresh tokens
Q6: Difference between Encryption & JWT?
- Encryption = hide data
- JWT = verify identity + send claims, not for hiding data
➢ ANNOTATIONS & WHY USED
@Configuration
- Marks a class that declares @Bean methods.
- Spring processes it to build beans for the application context (used in SecurityConfig).
@EnableWebSecurity
- Enables Spring Security integration and lets you customize the security filter chain.
@EnableMethodSecurity
- Enables method-level security annotations like @PreAuthorize, @RolesAllowed, etc.
@Component
- Marks a class as a Spring-managed bean.
- JwtFilter is a component so Spring will create and manage its lifecycle.
@Service
- Specialization of @Component for service layer beans (e.g., JwtService).
- Semantically indicates business logic / service responsibilities.
@RestController
- Controller whose methods return JSON (combines @Controller + @ResponseBody).
@Autowired
- Injects dependencies (field/setter/constructor injection).
- Prefer constructor injection for testability and immutability, but @Autowired is common.
@Bean
Marks a method producing a bean to be managed by Spring (e.g., AuthenticationManager,
AuthenticationProvider).
@PostMapping / @RequestBody
- Map HTTP POST to a method and bind request JSON to a Java object.
@Override
- Java annotation indicating you override a superclass method (e.g., doFilterInternal).
OncePerRequestFilter (extends)
- Spring filter that guarantees a single execution per request.
- Good for authentication filters (JwtFilter) so each HTTP request is processed once.
UsernamePasswordAuthenticationToken
- Represents a successful authentication (principal + credentials + authorities).
- We put this into SecurityContextHolder when token is valid.
WebAuthenticationDetailsSource
- Builds extra details (remote address/session id) and attaches them to authentication object.
SecurityContextHolder
- Holds SecurityContext (Authentication) for the current thread.
- Spring reads this to know "who is logged in".
addFilterBefore(jwtFilter, [Link])
- Registers your JWT filter before Spring's username/password filter.
- Ensures JWT token is processed before Spring tries default auth mechanisms.
[Link]
- Tells Spring not to keep session. Use for token-based (JWT) APIs.
AuthenticationManager / DaoAuthenticationProvider
- AuthenticationManager delegates authentication.
- DaoAuthenticationProvider checks username/password against UserDetailsService and a
PasswordEncoder.

IMPORTANT QUESTIONS (for interviews) + SHORT ANSWERS


Q: Why a JwtFilter and not simply read token in controllers?
A: Central place to validate token and set SecurityContext so all controllers use Spring Security
normally (no need to add token checks in every controller method).
Q: Why use OncePerRequestFilter?
A: Ensures filter runs exactly once per request; ideal for authentication checks.
Q: Why add JWT filter before UsernamePasswordAuthenticationFilter?
A: So token-based auth is attempted before the default form or basic auth; prevents unnecessary login
prompts.
Q: Why session stateless for JWT?
A: JWT holds authentication data; server doesn't need to store session state — improves scalability.
Q: Where should the JWT secret live?
A: Never hard-code. Keep in environment variables, secrets manager, or keystore (not in source
control).
Q: Why not regenerate secret on each startup (as in generateSecretKey used at runtime)?
A: If you regenerate, existing tokens immediately become invalid across restarts. Use a stable secret.
Q: How do you invalidate a JWT?
A: JWTs are stateless and can't be "deleted" from server — you need strategies:
- Short expiry + refresh tokens
- Maintain a server-side blacklist (token revocation list)
- Rotate secrets (with careful handling)
Q: How do you protect JWT from XSS or theft?
A: Prefer HttpOnly+Secure cookies (SameSite=strict/lax) for storage; or if using localStorage, ensure
strong XSS protection and short expiry.
Q: What if token is expired/invalid in JwtFilter?
A: Catch relevant exceptions, clear SecurityContext, and return 401/403 with proper message (do not
leak secrets).
Q: Why use BCrypt for password storage?
A: BCrypt hashes with salt and work factor — defends against rainbow-table and brute-force attacks.
Q: Is it safe to store user roles in JWT claims?
A: Yes, but be careful: claims are not encrypted. Do not store sensitive personal data in token payload.
Q: Should we load UserDetails on every request?
A: Not strictly necessary if roles/claims are trusted in JWT; but loading ensures latest user state (e.g.,
revoked role).
- Tradeoff: performance vs always-fresh data. Option: cache UserDetails.
Q: Why use AuthenticationManager in login endpoint?
A: It delegates to configured providers (e.g., DaoAuthenticationProvider) so password checking
respects the configured encoder.
Q: Why use [Link](...) inside filter instead of @Autowired
MyUserDetailsService?
A: Typically you can @Autowired MyUserDetailsService. Using ApplicationContext is sometimes
used to avoid circular dependency issues.
- Prefer constructor injection where possible and avoid circular references.

➢ JWT WORKFLOW (Step-by-step, simple)


1) CLIENT -> /register (POST)
- Sends username + password (+ role)
- Server hashes password (BCrypt) and saves user.
2) CLIENT -> /login (POST)
- Sends username + password
- Controller calls [Link](...)
- AuthenticationManager uses DaoAuthenticationProvider -> UserDetailsService ->
loadUserByUsername()
3) AUTH SUCCESS
- Controller asks JwtService to generateToken(username)
- JwtService builds token: [Link] (signed with server secret)
- Response returns token to client (Bearer token).
4) CLIENT stores token
- Option A: HttpOnly Secure cookie (recommended)
- Option B: localStorage/sessionStorage (less safe)
5) CLIENT -> Subsequent API request
- Adds header: Authorization: Bearer <token>
6) SERVER receives request
- [Link] intercepts request
- Reads Authorization header, extracts token, extracts username
7) JwtFilter validation

• Loads UserDetails (from DB or cache)


• Calls [Link](token, userDetails)
Check signature, expiration, and subject match
• If valid -> create UsernamePasswordAuthenticationToken and set into SecurityContextHolder

8) Controller executes
- Spring sees SecurityContextHolder has Authentication => request is treated as authenticated
- Authorization annotations (e.g., @PreAuthorize) check roles/authorities.
9) If token invalid or expired
- Filter rejects; return 401/403 and do not set SecurityContext.
10) Token refresh / logout
- Implement refresh token endpoint for long sessions
- For logout with stateless JWT implement revocation list or short expiry

SAMPLE INTERVIEW QUESTIONS (code-specific) + succinct answers


Q: What does JwtFilter do and why is it necessary?
A: It validates tokens on every request and populates SecurityContext so controllers can rely on
Spring Security.
Q: Why call [Link]().setAuthentication(...)?
A: So downstream code can check Authentication via
[Link]().getAuthentication().

Q: Why use UsernamePasswordAuthenticationToken with null credentials?


A: Credentials are not needed after successful validation; we pass principal + authorities.
Q: Why stateless sessions with JWT?
A: For scaling horizontally—no server-side session to replicate.
Q: How to handle token renewal securely?
A: Use a short-lived access token + longer-lived refresh token (refresh token must be stored securely
and can be revoked).
Q: How to store secret in production?
A: Use environment variables, HashiCorp Vault, AWS Secrets Manager, or a JKS/PKCS12 keystore.
Q: What is OAuth2?
A: An authorization framework where user grants limited access to their data without sharing
credentials.
Q: Difference between OAuth2 and JWT auth?

• OAuth2 delegates login to external providers (Google, GitHub).


• JWT is typically self-contained auth token issued by your own server.
Q: How does Spring Security know where to redirect for Google login?
A: Predefined provider configuration is built into Spring Boot starter. Just provide client-id and secret.
Q: Can I use multiple OAuth2 providers in same app?
A: Yes. Add multiple "[Link].*" entries (google, github, facebook).
Q: How do you customize login success?
A: Use http.oauth2Login().successHandler(customHandler).
Q: How to store OAuth2 user in DB after login?
A: Implement OAuth2UserService, load user attributes, and save/update user in database.
Q: What object stores OAuth2 user after login?
A: OAuth2AuthenticationToken + OAuth2User in SecurityContextHolder.
Q: Is OAuth2 login stateless?
A: By default it uses session (stateful). To make stateless, you’d integrate JWT after OAuth2.

[Link] → What it means?


1. Callback URL (Redirect URI)
- This is the address in your Spring app where Google sends the user back after login.
- You must configure the same redirect URI in Google Cloud Console.
2. Authorization Code Receiver
- After successful login with Google, Google sends a temporary "authorization code" (ticket).
- That code is received at this URL.
3. Code → Token Exchange
- Spring Security automatically takes that code and exchanges it with Google servers.
- It gets an "Access Token" (to access user data) and "ID Token" (user identity info).
4. Login Success
- Once tokens are received, Spring Security marks the user as AUTHENTICATED.
- User details (email, name, profile picture, etc.) become available in the SecurityContext.
5. Redirect to Your App
- By default, after login Spring redirects the user to `/` (home page).
- You can customize this to another page, e.g., `/dashboard` or `/welcome`.

You might also like