Spring_Boot
Spring_Boot
Auto Configuration
Opinionated defaults
Starter dependencies
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(DemoApplication.class, args);
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@GetMapping("/hello")
Tells Spring Boot to start scanning for components and auto-configure the
app.
1. @SpringBootApplication
SpringApplication.run(MyApp.class, args);
2. @RestController
@RestController
@GetMapping("/hello")
Used to handle HTTP GET, POST, PUT, and DELETE requests respectively
@GetMapping("/get")
@PostMapping("/post")
}
4. @Autowired
@Service
@RestController
@Autowired
@GetMapping("/serve")
return myService.serve();
my-boot-app/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/example/mybootapp/
│ │ ├── MyBootAppApplication.java
│ │ └── controller/
│ │ └── service/
│ └── resources/
│ ├── application.properties
├── pom.xml
Starter Dependencies
Common Starters:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
These files are used to define application configuration like server port,
database details, logging, etc.
application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
Activate a profile:
o via application.properties:
o spring.profiles.active=dev
# application-dev.properties
server.port=8081
spring.datasource.username=dev_user
# application-prod.properties
server.port=8080
spring.datasource.username=prod_user
Spring Boot makes it easy to interact with databases using Spring Data JPA.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
import jakarta.persistence.*;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
3. Repository Interface
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
@RestController
@RequestMapping("/users")
@Autowired
@PostMapping
return userRepository.save(user);
@GetMapping
return userRepository.findAll();
5. application.properties Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
Output Example
Visit: http://localhost:8080/h2-console
It's a part of Spring that simplifies data access using JPA. It provides ready-
to-use implementations for most database operations.
Spring Boot leverages Dependency Injection (DI) and Bean Management from the
core Spring Framework to achieve loose coupling and increase testability.
Types of DI in Spring
java
@Service
@RestController
this.myService = myService;
@GetMapping("/data")
return myService.getData();
Spring Beans
A bean is an object that is managed by the Spring container. Beans are created,
configured, and managed by Spring's IoC container.
Declaring a Bean
@Component
@Service
@Repository
@Controller
java
@Configuration
@Bean
Example:
application.properties
properties
app.name=MySpringApp
app.version=1.0.0
Java Class
java
@RestController
@Value("${app.name}")
@GetMapping("/info")
2. Using @ConfigurationProperties
Example:
application.properties
properties
app.details.name=SpringBootApp
app.details.version=2.5
app.details.owner=DevUser
Config Class
java
@Component
@ConfigurationProperties(prefix = "app.details")
Usage in Controller
java
@RestController
@Autowired
@GetMapping("/details")
4. Environment variables
yaml
app:
credentials:
username: admin
password: secret
Java Class
java
@Component
@ConfigurationProperties(prefix = "app.credentials")
Topic 8: Spring Boot REST APIs – Building CRUD with Spring MVC
Spring Boot makes it super easy to build RESTful web services using Spring MVC. This
topic covers creating a basic CRUD API.
1. REST Basics
Model Class
java
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Repository Interface
java
@Repository
Controller Class
java
@RestController
@RequestMapping("/students")
@Autowired
return repository.save(student);
@GetMapping
return repository.findAll();
@GetMapping("/{id}")
return repository.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
@PutMapping("/{id}")
student.setName(updated.getName());
student.setEmail(updated.getEmail());
return ResponseEntity.ok(repository.save(student));
}).orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
repository.delete(student);
return ResponseEntity.noContent().build();
}).orElse(ResponseEntity.notFound().build());
Q1: What annotations are used to build REST APIs in Spring Boot?
@RestController, @RequestMapping, @GetMapping, @PostMapping,
@PutMapping, @DeleteMapping
Topic 9: Spring Boot with Spring Data JPA – Repositories & Database Integration
Spring Data JPA simplifies the development of database access layers by abstracting
boilerplate code.
Component Description
1. Define Entity
4. Entity Example
java
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
5. Repository Example
java
6. Configuration (application.properties)
properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
java
java
@Query("SELECT p FROM Product p WHERE p.name = ?1")
Topic 10: Spring Boot Exception Handling – Global Error Handling with
@ControllerAdvice
Spring Boot provides a powerful way to handle exceptions globally and return custom
error responses.
2. Key Annotations
Annotation Purpose
java
super(message);
java
@ControllerAdvice
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleResourceNotFound(ResourceNotFoundException ex) {
@ExceptionHandler(Exception.class)
java
@RestControllerAdvice
@ExceptionHandler(ResourceNotFoundException.class)
errorDetails.put("error", ex.getMessage());
errorDetails.put("timestamp", LocalDateTime.now());
java
@GetMapping("/products/{id}")
return productRepository.findById(id)
}
Interview Questions with Answers
1. Key Concepts
Term Description
Add dependency:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3. Default Behavior
java
@Configuration
@EnableWebSecurity
@Override
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin123").roles("ADMIN")
.and()
.withUser("user").password("{noop}user123").roles("USER");
@Override
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
5. Key Classes/Annotations
Component Description
java
@RestController
@GetMapping("/admin/dashboard")
}
@GetMapping("/user/profile")
7. Password Encoding
java
@Bean
8. Custom UserDetailsService
java
@Service
@Autowired
@Override
return user.getRoles().stream()
.collect(Collectors.toList());
Topic 12: Spring Boot with Spring Data JPA – Repositories & Queries
Spring Data JPA simplifies data access by abstracting boilerplate code and giving you a
clean repository pattern using interfaces.
For MySQL:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
java
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
java
java
@RestController
@RequestMapping("/students")
@Autowired
@PostMapping
public Student save(@RequestBody Student student) {
return repo.save(student);
@GetMapping
return repo.findAll();
@GetMapping("/course/{course}")
return repo.findByCourse(course);
java
findByOr findByNameOrCourse(...) OR
java
Topic 13: Spring Boot RESTful API Development – Controllers & CRUD
Spring Boot makes it easy to build RESTful APIs with full CRUD (Create, Read, Update,
Delete) operations.
A RESTful API:
Is stateless.
Annotation Purpose
java
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
4. Example Repository
java
public interface StudentRepository extends JpaRepository<Student, Long> { }
5. REST Controller
java
@RestController
@RequestMapping("/api/students")
@Autowired
@PostMapping
return studentRepo.save(student);
@GetMapping
return studentRepo.findAll();
@GetMapping("/{id}")
return studentRepo.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PutMapping("/{id}")
return studentRepo.findById(id)
.map(student -> {
student.setName(newStudent.getName());
student.setCourse(newStudent.getCourse());
return ResponseEntity.ok(studentRepo.save(student));
}).orElse(ResponseEntity.notFound().build());
@DeleteMapping("/{id}")
return studentRepo.findById(id)
.map(student -> {
studentRepo.delete(student);
return ResponseEntity.noContent().build();
}).orElse(ResponseEntity.notFound().build());
Validation ensures data integrity, and proper exception handling improves API reliability.
Annotation Description
xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
java
java
@PostMapping("/students")
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(errors);
java
@ControllerAdvice
@ExceptionHandler(MethodArgumentNotValidException.class)
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleResourceNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
java
super(message);
1. What is AOP?
AOP allows modularizing concerns that cut across multiple classes or
methods.
Term Description
Annotation Purpose
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
java
@Aspect
@Component
@Before("execution(* com.myapp.service.*.*(..))")
java
@SpringBootApplication
@EnableAspectJAutoProxy
public class MyApp {
SpringApplication.run(MyApp.class, args);
Spring Data JPA simplifies the implementation of data access layers using JPA and
Hibernate under the hood.
2. Dependencies
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
</dependency>
properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
4. Entity Class
java
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
5. Repository Interface
java
save()
findById()
findAll()
deleteById()
count()
java
@Service
@Autowired
return userRepo.findAll();
}
java
java
super(message);
java
return userRepo.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with ID: " + id));
java
@ControllerAdvice
@ExceptionHandler(ResourceNotFoundException.class)
@ExceptionHandler(Exception.class)
java
Logging is essential for monitoring and debugging applications. Spring Boot uses SLF4J
with Logback as the default logging framework.
1. What is SLF4J?
It’s an abstraction layer for various logging frameworks (like Logback, Log4J,
java.util.logging).
Spring Boot uses Logback as its default logging implementation behind SLF4J.
Level Description
java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
@RestController
@GetMapping("/test")
logger.info("INFO message");
logger.debug("DEBUG message");
logger.error("ERROR message");
properties
logging.level.root=INFO
logging.level.com.yourpackage=DEBUG
logging.file.name=app.log
xml
<configuration>
<encoder>
</encoder>
</appender>
<root level="info">
</root>
</configuration>
Q3: How do you change the log level for a specific package?
Use logging.level.com.example=DEBUG in application.properties.
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Default credentials:
o Username: user
java
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@EnableWebSecurity
public class SecurityConfig {
@Bean
http
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin();
return http.build();
5. In-Memory Authentication
java
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Bean
.username("admin")
.password("password")
.roles("ADMIN")
.build();
Annotation Purpose
Session Fixation
Clickjacking
Q2: What happens when you add Spring Security to your Spring Boot app?
All endpoints become secured, and a default login form is shown.
Spring Boot Actuator helps you monitor and manage your application in production by
exposing several built-in endpoints related to health, metrics, environment, and more.
1. Adding the Actuator Dependency
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
properties
management.endpoints.web.exposure.include=health,info,metrics
Or to expose all:
properties
management.endpoints.web.exposure.include=*
Endpoint Purpose
java
@Bean
properties
management.endpoints.web.exposure.include=info
info.app.version=1.0.0
properties
management.endpoints.web.exposure.include=health,info
management.endpoint.health.roles=ADMIN
java
http
.authorizeHttpRequests()
.requestMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().authenticated();
Topic 21: Spring Boot – Building RESTful Web Services (CRUD APIs)
Spring Boot simplifies the development of RESTful APIs by using annotations and
automatic configurations.
Annotation Description
Model
java
Controller
java
@RestController
@RequestMapping("/students")
@GetMapping
@PostMapping
students.add(student);
@GetMapping("/{id}")
return students.stream()
.findFirst()
.orElse(null);
@PutMapping("/{id}")
if (s.getId().equals(id)) {
s.setName(updatedStudent.getName());
s.setEmail(updatedStudent.getEmail());
@DeleteMapping("/{id}")
3. Best Practices
Exception Description
java
@ControllerAdvice
@ExceptionHandler(ResourceNotFoundException.class)
@ExceptionHandler(Exception.class)
java
super(message);
java
java
@ExceptionHandler(ResourceNotFoundException.class)
ex.getMessage(),
LocalDateTime.now(),
);
Hibernate Validator is the reference implementation of the Bean Validation API (JSR
380) used in Spring Boot for validating user input.
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
java
java
@RestController
@RequestMapping("/users")
@PostMapping
java
@ControllerAdvice
@ExceptionHandler(MethodArgumentNotValidException.class)
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
Annotation Description
Lombok is a Java library that helps reduce boilerplate code like getters, setters,
constructors, toString(), etc., by using annotations.
For Maven:
xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
Make sure annotation processing is enabled in your IDE (e.g., IntelliJ or Eclipse).
2. Common Lombok Annotations
Annotation Purpose
3. Example
java
import lombok.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
}
Now you don’t need to write any constructors, getters, setters, or toString() manually.
4. Logging Example
java
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@GetMapping("/")
Interview Questions
Spring Boot Actuator provides production-ready features to help monitor and manage
your application — like checking health, metrics, environment properties, etc.
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
properties
management.endpoints.web.exposure.include=*
# management.endpoints.web.exposure.include=health,info
Endpoint Purpose
properties
management.endpoints.web.exposure.include=info
info.app.name=MySpringApp
info.app.version=1.0.0
properties
management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=when_authorized
Interview Questions
xml
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Also include:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. Configure application.properties
properties
management.endpoints.web.exposure.include=*
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true
3. Prometheus Setup
Install Prometheus
Configure prometheus.yml:
yaml
scrape_configs:
- job_name: 'spring-boot-app'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['localhost:8080']
4. Grafana Setup
Install Grafana
o CPU usage
o Memory consumption
java
@Autowired
MeterRegistry meterRegistry;
@PostConstruct
meterRegistry.counter("my.custom.counter").increment();
Interview Questions
Q1: What is Micrometer?
Micrometer is a metrics collection library backed by various monitoring tools like
Prometheus, Datadog, etc.
Logging is crucial for debugging, monitoring, and auditing application behavior. Spring
Boot provides built-in support for popular logging frameworks.
ERROR
WARN
INFO
DEBUG
TRACE
Configure in application.properties:
properties
logging.level.root=INFO
logging.level.com.yourpackage=DEBUG
logging.file.name=app.log
logging.file.path=/var/logs
properties
Graylog
These tools help centralize and analyze logs from multiple microservices.
6. Logging in Code
java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
Interview Questions
Q3: How can you change the logging level for a package?
Use logging.level.<package>=LEVEL in application.properties.
1. What is AOP?
AOP helps in separating cross-cutting concerns from the main business logic.
These are aspects that a ect multiple parts of the application (e.g., logging,
security).
2. AOP Terminology
Term Description
Advice Code that runs at a join point (e.g., before or after a method)
3. Types of Advice
@Around: Runs before and after the method (can modify behavior)
4. Basic Example
java
@Aspect
@Component
@Before("execution(* com.example.service.*.*(..))")
Spring Boot already includes Spring AOP. Just annotate configuration class with:
java
@EnableAspectJAutoProxy
Logging
Transaction Management
Security
Caching
Performance monitoring
Interview Questions
1. What is i18n?
i18n stands for Internationalization (first letter i, last letter n, and 18 letters in
between).
plaintext
src/main/resources/messages.properties // default
src/main/resources/messages_fr.properties // French
src/main/resources/messages_hi.properties // Hindi
Example:
properties
# messages.properties
greeting=Hello
# messages_fr.properties
greeting=Bonjour
# messages_hi.properties
greeting=नम े
java
@Bean
slr.setDefaultLocale(Locale.ENGLISH);
return slr;
}
java
@Bean
lci.setParamName("lang");
return lci;
@Override
registry.addInterceptor(localeChangeInterceptor());
java
@Autowired
Spring will automatically pick the correct message file based on the locale.
Interview Questions
like a summary PDF of all 30 topics, or maybe want to revise any specific topic