Spring Boot Basics
What is Spring Boot and why is it used?
Answer:
Spring Boot is an extension of the Spring Framework that simplifies application development.
It provides auto-configuration, embedded servers, and production-ready defaults, so developers can focus more on business logic instead of configuration.
In simple terms:
Spring Boot helps you build and run Spring applications faster with minimal setup.
What problems does Spring Boot solve?
Answer:
Spring Boot solves several common problems faced in traditional Spring development:
- Complex XML configuration
- Manual dependency management
- External server setup
- Environment-specific configuration issues
By handling these automatically, Spring Boot enables rapid development with minimal configuration.
“Spring Boot mainly reduces boilerplate code and speeds up application startup.”
What is the difference between Spring and Spring Boot?
Answer:
Spring is a powerful framework that provides features like dependency injection and transaction management.
Spring Boot is built on top of Spring and provides:
- Auto-configuration
- Embedded servers
- Opinionated defaults
Key difference:
Spring gives you flexibility, while Spring Boot gives you speed and convenience.
“Spring Boot lets you go from idea to running application in minutes.”
What are embedded servers in Spring Boot?
Answer:
Spring Boot provides embedded servers such as:
- Tomcat (default)
- Jetty
- Undertow
These servers are packaged inside the application itself.
This means you can run your application as a standalone JAR without deploying it to an external server.
“You just run java -jar app.jar, and your application is live.”
What is @SpringBootApplication?
Answer:
@SpringBootApplication is a convenience annotation that combines three important annotations:
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan
It marks the main entry point of a Spring Boot application and triggers auto-configuration and component scanning.
“This single annotation replaces multiple Spring annotations.”
What is @EnableAutoConfiguration?
Answer:
@EnableAutoConfiguration tells Spring Boot to automatically configure beans based on:
- Classpath dependencies
- Application properties
- Existing beans
It reduces the need for manual configuration.
Real-world example:
“If Spring Boot finds JPA in the classpath, it automatically configures a DataSource and EntityManager.”
What is @ComponentScan?
Answer:
@ComponentScan tells Spring where to look for components like:
- @Component
- @Service
- @Repository
- @Controller
By default, it scans the package of the main class and all its sub-packages.
Interview line:
“Wrong package structure is a common reason for beans not getting created.”
Difference between @Component, @Service, and @Repository?
Answer:
All three are stereotype annotations used for component scanning:
- @Component – Generic stereotype
- @Service – Business logic layer
- @Repository – Data access layer with exception translation
Functionally similar, but semantically they improve readability and design.
“They help developers understand the role of a class at a glance.”
What is Spring Boot Starter?
Answer:
Spring Boot Starters are predefined dependency bundles that simplify dependency management.
Examples:
- spring-boot-starter-web
- spring-boot-starter-data-jpa
- spring-boot-starter-security
Instead of adding multiple dependencies, you add one starter.
“Starters promote convention over configuration.”
What is application.properties or application.yml?
Answer:
These files are used to configure Spring Boot applications.
They allow you to define:
- Server port
- Database configuration
- Logging levels
- Custom properties
application.yml is preferred for complex hierarchical configurations.
“This is where environment-specific configuration becomes easy.”
Spring Boot Annotations
What is the difference between @Component, @Service, and @Repository?
Answer:
All three are stereotype annotations used for component scanning in Spring Boot.
They tell Spring that a class should be managed as a bean.
Conceptual Explanation
Even though these annotations behave similarly, they are used for different layers of the application:
- @Component → Generic component
- @Service → Business logic layer
- @Repository → Data access layer
Spring uses them mainly for readability and clean architecture.
Real-world Project Usage
In real projects:
- Business logic classes are annotated with @Service
- DAO or repository classes are annotated with @Repository
- Utility or helper classes use @Component
This helps any developer instantly understand the responsibility of a class.
Interview Takeaway
“Functionally similar, but semantically different — used to improve code readability and design.”
What is @SpringBootApplication and why is it important?
Answer:
@SpringBootApplication is a meta-annotation that marks the main class of a Spring Boot application.
It enables auto-configuration and component scanning.
What does it internally contain?
It combines three annotations:
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan
Instead of writing all three separately, Spring Boot provides this single annotation.
Why is it important?
- Acts as the entry point of the application
- Triggers auto-configuration
- Scans components automatically
Interview Line
“@SpringBootApplication replaces multiple Spring annotations and simplifies application startup.”
What is @EnableAutoConfiguration?
Answer:
@EnableAutoConfiguration allows Spring Boot to automatically configure beans based on the application’s classpath and properties.
How auto-configuration works
Spring Boot checks:
- Which libraries are present in the classpath
- What beans already exist
- What properties are defined
Based on this, it automatically creates and configures required beans.
Real-world Example
If Spring Boot finds:
- spring-boot-starter-data-jpa
It automatically configures:
- DataSource
- EntityManager
- TransactionManager
Interview Takeaway
“Auto-configuration removes the need for manual bean definitions.”
What is @ComponentScan and how does it work?
Answer:
@ComponentScan tells Spring where to search for Spring-managed components.
Default behavior
Spring Boot scans:
- The package of the main class
- All its sub-packages
If a component is outside this package structure, it will not be detected.
Common Interview Pitfall
Many issues occur when:
- Main class is in the wrong package
- Components are placed outside scan scope
Interview Line
“Incorrect package structure is a common cause of bean-not-found issues.”
What is the difference between @Configuration and @Component?
Answer:
Both annotations define Spring beans, but they behave differently.
Key Difference
- @Configuration ensures singleton behavior using proxying
- @Component does not guarantee proxy-based bean behavior
This matters when one bean method calls another bean method.
When to use
- Use @Configuration for configuration classes
- Use @Component for simple components
Interview Line
“@Configuration is used for defining beans with full Spring lifecycle support.”
What is @Bean and when should it be used?
Answer:
@Bean is used to explicitly define a Spring-managed bean inside a configuration class.
When do we need @Bean?
- When using third-party libraries
- When we cannot annotate the class directly
- When we need custom initialization logic
Real-world Example
Creating beans for:
- ObjectMapper
- RestTemplate
- External SDKs
Interview Tip
“@Bean gives fine-grained control over bean creation.”
What is the difference between @Autowired and constructor injection?
Answer:
@Autowired injects dependencies automatically, but constructor injection is preferred.
Why constructor injection is better
- Makes dependencies explicit
- Promotes immutability
- Easier to test
- Avoids null pointer issues
Spring officially recommends constructor injection.
Interview Line
“Constructor injection is the best practice for dependency injection.”
What is @Qualifier and why is it used?
Answer:
@Qualifier is used when multiple beans of the same type exist.
It tells Spring which specific bean should be injected.
Example Scenario
If two beans implement the same interface:
- Spring gets confused
- @Qualifier resolves ambiguity
Interview Line
“@Qualifier is used to resolve multiple bean conflicts.”
What is @Primary?
Answer:
@Primary marks a bean as the default choice when multiple beans of the same type are present.
Difference from @Qualifier
- @Primary → global preference
- @Qualifier → specific selection
Interview Line
“@Primary provides a default bean when ambiguity exists.”
What is @Valueannotation used for?
Answer:
@Value is used to inject values from:
- application.properties
- environment variables
- system properties
Common Use Cases
- Reading configuration values
- Injecting constants
- Externalizing configuration
Interview Line
“@Value helps externalize configuration from code.”
Spring Boot Auto configuration
What is Auto-Configuration?
Question: What is Auto-Configuration in Spring Boot?
Answer: Spring Boot’s Auto-Configuration is a feature that automatically configures beans in the Spring Application Context based on the classpath settings, environment variables, and properties.
- It reduces boilerplate code.
- It uses @EnableAutoConfiguration (implicitly included in @SpringBootApplication).
- It scans META-INF/spring.factories to load configuration classes.
Example: If spring-boot-starter-data-jpa is on the classpath, Spring Boot automatically configures:
- EntityManagerFactory
- DataSource
- TransactionManager
How does Spring Boot decide what to configure?
Answer:
- Auto-Configuration classes are loaded via spring.factories.
- Each configuration class uses conditional annotations like:
- @ConditionalOnClass → activates if a class is present in classpath.
- @ConditionalOnMissingBean → activates if a bean is not already defined.
- @ConditionalOnProperty → activates if a property is set in application.properties.
Example:
java
@Configuration
@ConditionalOnClass(DataSource.class)
public class DataSourceAutoConfiguration {
// Configures a DataSource bean if none exists
}
What annotations are commonly used in Auto-Configuration?
Answer:
- @EnableAutoConfiguration → enables auto-configuration.
- @SpringBootApplication → includes @EnableAutoConfiguration, @Configuration, and @ComponentScan.
- @ConditionalOnClass → checks for class presence.
- @ConditionalOnMissingBean → prevents duplicate beans.
- @ConditionalOnProperty → activates based on property values.
Question: How can you customize or disable Auto-Configuration?
Answer:
- Disable specific auto-configurations:
java
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApp { }
- Control via properties:
properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
- Override beans manually: If you define your own DataSource bean, Spring Boot won’t create one automatically.
Scenario: You add spring-boot-starter-web dependency.
- Auto-configures DispatcherServlet, DefaultErrorController, Jackson ObjectMapper.
- You don’t need to manually configure these unless customization is required.
What is the role of spring.factories in Auto-Configuration?
- It lists all auto-configuration classes that Spring Boot should load.
How does Spring Boot avoid configuring beans unnecessarily?
- By using conditional annotations (
@ConditionalOnClass,@ConditionalOnMissingBean).
Can you disable Auto-Configuration globally?
- Yes, using
@SpringBootApplication(exclude = {...})orspring.autoconfigure.excludeproperty.
What happens if you define your own bean that conflicts with Auto-Configuration?
- Your bean takes precedence; auto-configured bean is skipped.
Why is Auto-Configuration important in microservices?
- It speeds up development, reduces boilerplate, and ensures consistent configurations across services.
Rest API & Controllers
Spring Data JPA & Hibernate
1. What is JPA?
Answer:
JPA stands for Java Persistence API.
It is a specification, not an implementation, that defines how Java objects are mapped to relational database tables.
In simple terms:
JPA defines what to do, but not how to do it.
JPA provides:
- Entity mapping
- Relationship mapping
- Query language (JPQL)
- Persistence context
- Transaction handling guidelines
Common JPA implementations:
- Hibernate (most popular)
- EclipseLink
- OpenJPA
In Spring Boot, Hibernate is used by default as the JPA provider.
2. What is Hibernate?
Answer:
Hibernate is an ORM (Object Relational Mapping) framework and a JPA implementation.
Hibernate:
- Converts Java objects into database rows
- Converts database rows back into Java objects
- Handles SQL generation automatically
- Manages caching and performance optimizations
Relationship:
JPA = Specification
Hibernate = Implementation
3. What is Spring Data JPA?
Answer:
Spring Data JPA is a Spring abstraction layer built on top of JPA and Hibernate.
Its main goal is to:
- Reduce boilerplate code
- Eliminate DAO implementations
- Simplify database access
With Spring Data JPA:
- No need to write implementation classes
- Repository interfaces are enough
- CRUD operations are auto-generated
Example:
public interface UserRepository extends JpaRepository<User, Long> {
}
Spring creates the implementation at runtime.
4. Difference between JPA and Hibernate
| JPA | Hibernate |
| Specification | Implementation |
| Defines rules | Provides actual logic |
| Vendor independent | Vendor specific |
| No ORM engine | Full ORM engine |
Hibernate implements JPA, but also provides extra features beyond JPA.
5. What is ORM?
Answer:
ORM stands for Object Relational Mapping.
ORM maps:
- Java Class → Database Table
- Java Object → Table Row
- Java Field → Table Column
Benefits:
- No manual SQL
- Database independent
- Cleaner and maintainable code
Hibernate is the most widely used ORM framework in Java.
6. What is an Entity?
Answer:
An Entity is a persistent Java class that represents a database table.
Rules:
- Must be annotated with @Entity
- Must have a primary key (@Id)
- Must have a default constructor
Example:
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
7. What is @Table annotation?
Answer:
@Table is used to map an entity to a specific database table.
Example:
@Entity
@Table(name = “users”)
public class User {
}
If @Table is not used, Hibernate uses the class name as table name.
8. What is @Id and @GeneratedValue?
Answer:
@Id defines the primary key of the entity.
@GeneratedValue tells Hibernate how to generate primary key values.
Common strategies:
- AUTO
- IDENTITY
- SEQUENCE
- TABLE
Example:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
9. What is a Repository in Spring Data JPA?
Answer:
A Repository is an interface that provides database operations.
Spring Data provides:
- CrudRepository
- JpaRepository
- PagingAndSortingRepository
Most commonly used:
JpaRepository<Entity, ID>
It provides:
- CRUD
- Pagination
- Sorting
- Batch operations
10. Difference between CrudRepository and JpaRepository
| CrudRepository | JpaRepository |
| Basic CRUD | Advanced CRUD |
| No pagination | Supports pagination |
| No batch | Batch operations |
| Lightweight | Feature-rich |
Always prefer JpaRepository in Spring Boot projects.
11. How does Spring Data JPA generate queries?
Answer:
Spring Data JPA generates queries in three ways:
1️⃣ Method Name Queries
findByName(String name)
findByEmailAndStatus(String email, String status)
2️⃣ JPQL using @Query
@Query(“select u from User u where u.name = :name”)
3️⃣ Native Queries
@Query(value = “select * from users”, nativeQuery = true)
12. What is JPQL?
Answer:
JPQL stands for Java Persistence Query Language.
It:
- Works on entities, not tables
- Is database independent
- Gets converted into SQL internally
Example:
select u from User u where u.name = ‘John’
13. What is Persistence Context?
Answer:
Persistence Context is a first-level cache that stores entity objects.
Key points:
- Managed by EntityManager
- One persistence context per transaction
- Prevents duplicate database calls
Example:
User u1 = em.find(User.class, 1L);
User u2 = em.find(User.class, 1L);
// Only one DB call
14. Difference between save() and saveAndFlush()
| save() | saveAndFlush() |
| Saves in context | Saves immediately |
| Flush later | Flush now |
| Faster | Slower |
Use saveAndFlush() only when immediate DB sync is required.
15. What is Lazy and Eager fetching?
Answer:
Fetching defines when related entities are loaded.
- LAZY → Load only when accessed
- EAGER → Load immediately
Example:
@OneToMany(fetch = FetchType.LAZY)
Default:
- @OneToMany → LAZY
- @ManyToOne → EAGER
16. What is N+1 problem?
Answer:
N+1 problem occurs when:
- One query fetches parent entities
- N additional queries fetch child entities
Example:
1 query → Orders
N queries → OrderItems
Solution:
- JOIN FETCH
- EntityGraph
- Batch fetching
17. What is @Transactional?
Answer:
@Transactional ensures:
- Atomicity
- Consistency
- Rollback on failure
If any exception occurs:
- Transaction is rolled back automatically
Best practice:
- Use at service layer
- Avoid on controllers
18. Difference between Hibernate and JDBC
| JDBC | Hibernate |
| Manual SQL | Auto SQL |
| Boilerplate | Clean code |
| No caching | Caching |
| Error-prone | Safe |
19. Real-time Interview Question
Q: Why do we still use Hibernate when SQL is faster?
Answer:
Hibernate improves:
- Developer productivity
- Code maintainability
- Database portability
Performance can be optimized using:
- Indexing
- Native queries
- Caching
Hibernate is not slow; bad usage is slow.
20. When should you NOT use JPA?
Answer:
Avoid JPA when:
- Application is extremely SQL-heavy
- Complex reporting queries
- Stored procedures dominate
- Micro-optimizations are critical
In such cases:
- Use JDBC / jOOQ / MyBatis
Spring Boot Security
Spring Boot Security – Introduction (Video Intro Script)
In this section, we will understand how Spring Boot Security works internally, how authentication and authorization are handled, and how to secure REST APIs using modern approaches like JWT and OAuth2.
1. What is Spring Security?
Answer:
Spring Security is a powerful and customizable security framework used to secure Spring and Spring Boot applications.
It provides:
- Authentication (Who are you?)
- Authorization (What can you access?)
- Protection against common attacks
Spring Security is:
- Filter-based
- Highly configurable
- Integrated deeply with Spring ecosystem
2. What are the main features of Spring Security?
Answer:
Spring Security provides:
- Authentication & Authorization
- CSRF protection
- Session management
- Password encoding
- OAuth2 & JWT support
- Method-level security
- Protection against attacks like:
- CSRF
- Clickjacking
- Session fixation
3. What is Authentication?
Answer:
Authentication is the process of verifying the identity of a user.
Example:
- Username + Password
- Token
- OTP
- Biometric
If authentication fails → user is not logged in.
4. What is Authorization?
Answer:
Authorization determines what an authenticated user is allowed to access.
Example:
- USER can view profile
- ADMIN can delete users
Authentication comes first, then authorization.
5. Difference between Authentication and Authorization
| Authentication | Authorization |
| Who you are | What you can do |
| Login process | Access control |
| Happens first | Happens after |
| Credentials based | Role/permission based |
6. How does Spring Security work internally?
Answer (Very important interview question):
Spring Security works using a chain of filters.
High-level flow:
Request → Security Filters → Authentication → Authorization → Controller
Key components:
- Security Filter Chain
- AuthenticationManager
- AuthenticationProvider
- UserDetailsService
7. What is Security Filter Chain?
Answer:
Spring Security intercepts every HTTP request using a filter chain.
Filters handle:
- Login
- Token validation
- Session checks
- CSRF validation
In Spring Boot 3+, configuration is done using:
SecurityFilterChain
8. What is UserDetailsService?
Answer:
UserDetailsService is used to load user information from a data source.
It has one method:
UserDetails loadUserByUsername(String username)
Spring Security uses this during authentication.
9. What is UserDetails?
Answer:
UserDetails represents authenticated user information.
It contains:
- Username
- Password
- Roles
- Account status (locked, expired, etc.)
Custom user entities often implement UserDetails.
10. What is AuthenticationManager?
Answer:
AuthenticationManager is responsible for:
- Accepting authentication request
- Delegating to AuthenticationProvider
- Returning authenticated user
It acts as a bridge between filters and providers.
11. What is AuthenticationProvider?
Answer:
AuthenticationProvider contains actual authentication logic.
Examples:
- UsernamePasswordAuthenticationProvider
- JWTAuthenticationProvider
You can create custom providers for advanced scenarios.
12. What is PasswordEncoder?
Answer:
PasswordEncoder is used to hash passwords before storing or comparing.
Common encoders:
- BCryptPasswordEncoder (recommended)
- NoOpPasswordEncoder (NOT recommended)
Example:
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
13. Why should we never store plain text passwords?
Answer:
Storing plain text passwords:
- Is a major security risk
- Violates security standards
- Can expose user data in case of breach
Hashed passwords:
- Cannot be reversed
- Protect user data
14. What is CSRF?
Answer:
CSRF stands for Cross-Site Request Forgery.
It is an attack where:
- A logged-in user unknowingly performs an action
Example:
- Bank transfer triggered via malicious link
Spring Security:
- Enables CSRF protection by default
- Mostly needed for browser-based apps
15. Why is CSRF disabled for REST APIs?
Answer (Interview favorite):
REST APIs are:
- Stateless
- Token-based (JWT)
Since:
- No session cookies are used
- Tokens are sent explicitly
CSRF protection is usually disabled for REST APIs.
16. What is JWT?
Answer:
JWT stands for JSON Web Token.
It is a compact, self-contained token that contains:
- User information
- Expiry time
- Signature
JWT is:
- Stateless
- Scalable
- Ideal for microservices
17. JWT Authentication Flow
Answer:
1️⃣ User logs in with credentials
2️⃣ Server generates JWT
3️⃣ Client stores JWT
4️⃣ Client sends JWT in every request
5️⃣ Server validates JWT
No session is stored on the server.
18. Difference between Session-based and JWT-based authentication
| Session | JWT |
| Stateful | Stateless |
| Stored on server | Stored on client |
| Less scalable | Highly scalable |
| Cookie based | Header based |
19. What is OAuth2?
Answer:
OAuth2 is an authorization framework that allows:
- Third-party applications
- Secure access without sharing passwords
Example:
- Login with Google
- Login with GitHub
OAuth2 focuses on authorization, not authentication.
20. What is Role-based access control?
Answer:
Access is controlled using roles like:
- ROLE_USER
- ROLE_ADMIN
Example:
@PreAuthorize(“hasRole(‘ADMIN’)”)
Roles define what actions users can perform.
21. What is Method-Level Security?
Answer:
Method-level security allows you to secure:
- Service methods
- Controller methods
Annotations:
- @PreAuthorize
- @PostAuthorize
- @Secured
Example:
@PreAuthorize(“hasRole(‘ADMIN’)”)
public void deleteUser() {}
22. What is @EnableMethodSecurity?
Answer:
It enables method-level security annotations.
Example:
@EnableMethodSecurity
Required for:
- @PreAuthorize
- @PostAuthorize
23. What is CORS?
Answer:
CORS stands for Cross-Origin Resource Sharing.
It controls:
- Which domains can access APIs
- Which HTTP methods are allowed
Important for:
- Frontend + backend separation
24. Real-time Interview Question
Q: Why Spring Security is considered complex?
Answer:
Because:
- It uses filter chains
- Has many internal components
- Highly configurable
Once the flow is understood, it becomes very powerful.
25. When should you use Spring Security?
Answer:
Use Spring Security when:
- Application has users
- APIs need protection
- Role-based access is required
- OAuth2/JWT is needed
Exception Handling & Validation
Actuator & Monitoring
Spring Boot Actuator & Monitoring – 20 Interview Questions & Answers
🟢 Beginner Level (1–7)
1. What is Spring Boot Actuator?
- Answer: A set of production-ready tools that expose endpoints for monitoring and managing applications.
- Example: /actuator/health, /actuator/metrics.
2. How do you enable Actuator in a Spring Boot project?
- Add dependency:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
- Configure endpoints in application.properties.
3. Which Actuator endpoints are exposed by default?
- Default: /actuator/health, /actuator/info.
- Others must be explicitly enabled via:
- management.endpoints.web.exposure.include=*
4. What information does /actuator/health provide?
- Shows application health status: UP, DOWN, or custom states.
- Can include DB connectivity, disk space, external API checks.
5. What is /actuator/info used for?
- Displays application metadata like version, description, build info.
- Example:
- info.app.name=Interview Prep
- info.app.version=1.0.0
6. How do you customize Actuator endpoints?
- Change base path:
- management.endpoints.web.base-path=/monitor
- Disable specific endpoints:
- management.endpoint.shutdown.enabled=false
7. Why is Actuator important in microservices?
- Provides visibility into service health and metrics.
- Helps with service discovery and load balancing in Kubernetes/Eureka setups.
🟡 Intermediate Level (8–14)
8. How do you secure Actuator endpoints?
- Use Spring Security:
- http.authorizeRequests()
- .requestMatchers(“/actuator/**”).hasRole(“ADMIN”)
- .anyRequest().authenticated();
9. What is Micrometer in Spring Boot?
- A metrics facade used by Actuator.
- Supports integration with Prometheus, Grafana, Datadog, New Relic.
10. How do you expose metrics to Prometheus?
- Enable Prometheus export:
- management.metrics.export.prometheus.enabled=true
- Access via /actuator/prometheus.
11. How do you create a custom Health Indicator?
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean dbUp = checkDatabaseConnection();
return dbUp ? Health.up().build() : Health.down().withDetail(“error”, “DB not reachable”).build();
}
}
12. What is /actuator/metrics used for?
- Provides JVM, system, and custom metrics:
- Memory usage
- GC stats
- HTTP request latency
13. How do you change log levels at runtime?
- Use /actuator/loggers.
- Example: POST /actuator/loggers/com.example with JSON:
- { “configuredLevel”: “DEBUG” }
14. What is /actuator/threaddump?
- Provides a snapshot of all threads.
- Useful for debugging deadlocks or performance bottlenecks.
🔴 Advanced Level (15–20)
15. How do you monitor distributed microservices with Actuator?
- Combine Actuator with Spring Cloud.
- Use Spring Boot Admin to aggregate health/metrics across services.
16. How do you integrate Actuator with Grafana dashboards?
- Export metrics via Prometheus.
- Grafana queries Prometheus to visualize CPU, memory, request latency.
17. What is /actuator/httptrace?
- Shows last 100 HTTP requests (method, status, time).
- Must be enabled with:
- management.trace.http.enabled=true
18. How do you implement custom metrics?
@Autowired
MeterRegistry registry;
@PostConstruct
public void init() {
registry.counter(“custom.orders.created”).increment();
}
19. How do you monitor JVM memory usage?
- /actuator/metrics/jvm.memory.used
- Example output: value=12345678, unit=bytes.
20. Real-world scenario: Debugging with Actuator
- Problem: API latency spikes.
- Solution: /actuator/metrics showed high DB query times.
- Fix: Added caching + optimized queries.
- Result: Latency reduced by 60%.