CapgeminiJavaInterviewQuestions (1)
CapgeminiJavaInterviewQuestions (1)
Spring Framework?
Answer:
Spring Boot is an extension of the Spring Framework that simplifies the development of
Java applications by providing auto-configuration, embedded servers, and a convention-
over-configuration approach.
Key Differences:
Example:
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class, args);
}
}
Example:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
Example:
@Component
class ServiceA {
public void printMessage() {
System.out.println("Hello from ServiceA!");
}
}
@Component
class ServiceB {
private final ServiceA serviceA;
Annotation Purpose
@Component Generic annotation for Spring Beans. Used when no specific role is
defined.
Used for DAO (Data Access Layer) components and enables exception
@Repository
translation.
Example:
@Component
class GeneralComponent {}
@Service
class MyService {}
@Repository
class MyRepository {}
Answer:
Spring Boot provides global exception handling using @ControllerAdvice and
@ExceptionHandler .
Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("Something went wrong",
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Answer:
Spring Boot makes REST API development simple using @RestController and
@RequestMapping .
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<String> getUser(@PathVariable int id) {
return ResponseEntity.ok("User with ID: " + id);
}
@PostMapping
public ResponseEntity<String> createUser(@RequestBody String user) {
return ResponseEntity.status(HttpStatus.CREATED).body("User Created: " +
user);
}
}
Key Annotations:
@RestController → Marks a class as a REST API controller
@GetMapping , @PostMapping , etc. → Define HTTP methods
@PathVariable → Extracts values from URL
@RequestBody → Reads request body
Key Features:
Health Checks ( /actuator/health )
Metrics ( /actuator/metrics )
Environment Info ( /actuator/env )
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2 Configure application.properties :
management.endpoints.web.exposure.include=*
http://localhost:8080/actuator/health
Answer:
A Circuit Breaker prevents system failures by stopping calls to a failing service and
providing a fallback response.
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>
@Service
public class InventoryService {
Key Differences:
Difficult, scales as a
Scalability Easy, scale individual services
whole
Example:
Monolithic: One large app handling users, payments, and orders.
Microservices: Separate services for users, payments, and orders, communicating
via REST or messaging.
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://USER-SERVICE
predicates:
- Path=/users/**
Example:
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Answer:
A Circuit Breaker prevents cascading failures by stopping calls to a failing service
and returning a fallback response.
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>
2 Use @CircuitBreaker in your service:
@Service
public class InventoryService {
Example:
@FeignClient(name = "order-service")
public interface OrderServiceClient {
@GetMapping("/orders/{id}")
Order getOrder(@PathVariable Long id);
}
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
Answer:
Spring Security and JWT (JSON Web Tokens) are commonly used for authentication.
management.endpoints.web.exposure.include=*
Answer:
Since each microservice has its own database, transactions must be handled
differently.