J2EE - Interview questions and answers

 sega pattern,

Pragrams for : 11111: 1.1.1.11 1.1.11.1 1.11.1.1 11.1.1.1

Lamdam: when it is required and not required

Projects tell

Why change company

Find duplicates in java8

Factory pattern, abstract factory




Microservices using SpringBoot | Full Example : https://www.youtube.com/watch?v=BnknNTN8icw&pp=ygUZc3ByaW5nIGJvb3QgbWljcm9zZXJ2aWNlcw%3D%3D

daily code buffer - https://www.youtube.com/watch?v=BnknNTN8icw


@SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.


@RestController annotation in order to simplify the creation of RESTful web services. It’s a convenient annotation that combines @Controller and @ResponseBody, which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation. ( from Spring 4.0 introduced )


@ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.

If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.

ResponseEntity is a generic type. Consequently, we can use any type as the response body


1. What are microservices? 

Microservices is an architectural style that structures an application as a collection of small, loosely coupled, and independently deployable services. 

Each service represents a specific business capability and can be developed, deployed, and scaled independently. 


2. What is Spring Boot? 

Spring Boot is a framework built on top of the Spring framework that simplifies the development of Java applications, including microservices. 

It provides a convention-over-configuration approach, auto-configuration, and embedded servers, allowing developers to quickly create 

production-ready microservices with minimal setup. 

Spring Boot is basically an extension of the Spring framework which eliminated the boilerplate configurations required for setting up a Spring application.


Spring Boot is an opinionated framework that helps developers build Spring-based applications quickly and easily. 

The main goal of Spring Boot is to quickly create Spring-based applications 

without requiring developers to write the same boilerplate configuration again and again.

3. What are the advantages of using Spring Boot for microservices?

Simplified development: Spring Boot provides a range of features and defaults, reducing the amount of code and configuration required to develop microservices. 


Auto-configuration: It automatically configures various components based on classpath dependencies, reducing the need for manual configuration. 


Embedded servers: Spring Boot includes embedded servers like Tomcat, Jetty, or Undertow, making it easy to deploy microservices as standalone JAR files. 


Cloud-native support: Spring Boot integrates well with cloud platforms and provides support for building cloud-native microservices. 

4. How do you communicate between microservices in Spring Boot? 

In Spring Boot, microservices can communicate with each other using various mechanisms: 


Synchronous HTTP/REST: Microservices can communicate via HTTP using RESTful APIs, exchanging data in JSON or XML formats. For example, 

Spring Boot provides RestTamplete, and WebClient classes to make REST API calls from one microservice to another microservice.


Messaging: Asynchronous communication can be achieved using message queues or message brokers like RabbitMQ or Apache Kafka. 


Service Discovery: Microservices can use service discovery mechanisms like Netflix Eureka or 

Spring Cloud Consul to locate and communicate with other services dynamically. 

7. What is circuit breaking in microservices and how is it implemented in Spring Boot? 

Circuit breaking is a design pattern used to handle and prevent cascading failures in microservice architectures. 

It involves monitoring the calls to external services and, if a certain threshold of failures is reached, 

tripping a circuit breaker to stop further requests and return a fallback response. 


In Spring Boot, circuit breaking can be implemented using libraries like Netflix Hystrix or Resilience4j, 

which provide annotations and configuration options to define circuit breakers and fallback behaviors.


11. What is Spring Cloud Circuit Breaker?

Inter-service Communication is common in the Microservice architecture, if one of the services is down, 

the other service which is communicating with it should be able to handle this failure gracefully. 


Spring Cloud provides Spring Cloud Circuit Breaker module to implement the Circuit Breaker pattern in the Microservices project.


Spring Cloud Circuit breaker provides an abstraction across different circuit breaker implementations. 

It provides a consistent API to use in your applications allowing you the developer to choose the circuit breaker implementation

that best fits your needs for your app. 


Supported Implementations :

Resilience4J 

Spring Retry


9. What is API Gateway in microservices and how does it help? 

An API Gateway is a service that acts as an entry point for all client requests in a microservices architecture. 

It sits between the clients and the microservices, routing requests, handling authentication/authorization, enforcing security, 

and providing additional cross-cutting concerns like rate limiting, logging, and monitoring. API Gateways centralize these concerns, 

simplifying the clients' interactions with the microservices. 


14. Feign : What is Spring Cloud OpenFeign?

Feign is a declarative web service client. It makes writing web service clients easier. 


To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. 


Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and 

for using the same HttpMessageConverters used by default in Spring Web. 


Spring Cloud integrates Eureka, as well as Spring Cloud LoadBalancer to provide a load-balanced HTTP client when using Feign.


<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>


@SpringBootApplication

@EnableFeignClients

public class Application {


    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }


}


@FeignClient(name = "giveYourServiceName", url = "provideYourUrlHere", path = "provideYourContextPathHere")

public interface AddressClient {


    @GetMapping("/address/{id}")

    public ResponseEntity<AddressResponse> getAddressByEmployeeId(@PathVariable("id") int id);


}


@Service

public class EmployeeService {


    // More Code Here

    // -------------

    // Spring will create the implementation

    // for this class

    // and will inject the bean here (proxy)

    @Autowired

    private AddressClient addressClient;


    public EmployeeResponse getEmployeeById(int id) {

    

        // More Code Here


        // Using FeignClient

        ResponseEntity<AddressResponse> addressResponse = addressClient.getAddressByEmployeeId(id);

        employeeResponse.setAddressResponse(addressResponse.getBody());


        return employeeResponse;

    }


}

----

Micro services communication through:

1. RestTemplate

2. FeignClient

3. Apache Kafka

Apache Kafka:

- Apache Kafka is a distributed streaming platform that is commonly used for building real-time data pipelines and streaming applications.

- Kafka is designed for handling large volumes of data and is optimized for high-throughput, fault-tolerance, and scalability.

- It is often used for asynchronous communication between microservices, where one service produces messages to Kafka topics and other services consume these messages.

- Kafka is well-suited for scenarios where you need to process large amounts of data in real-time and where message ordering and fault-tolerance are important.

FeignClient:

- FeignClient is a declarative HTTP client developed by Netflix that simplifies the process of making HTTP requests in Java applications.

- It integrates well with Spring Cloud and allows you to define interfaces with annotated methods that describe the HTTP API endpoints.

- FeignClient handles the generation of HTTP requests and responses, making it easier to interact with other services over HTTP.

- It is a good choice for synchronous communication between microservices when you need to make RESTful API calls.

RestTemplate:

- RestTemplate is a synchronous HTTP client that is part of the Spring Framework and is commonly used for making HTTP requests in Java applications.

- It provides a simple API for interacting with RESTful web services and handling HTTP responses.

- RestTemplate is widely used in Spring applications for making REST API calls to other services.

- However, as of Spring 5, RestTemplate is deprecated in favor of the WebClient, which is a more modern, non-blocking, reactive HTTP client.


----

2. Explain a few important Spring Boot Key features?

Let me a list of a few key features of the Spring boot and we will discuss each key feature briefly.

Spring Boot starters

Spring Boot autoconfiguration

Elegant configuration management

Spring Boot Actuator

Easy-to-use embedded servlet container support

1. Spring Boot Starters

Starters are a set of opinionated dependencies that simplify dependency management. They encapsulate common configurations and dependencies 

needed for specific functionalities, such as database connectivity, security, web services, and more. Starters make it easy to add required 

dependencies with minimal effort and reduce version compatibility issues. 


For example, the spring-boot-starter-data-jpa starter module includes all the dependencies required to use Spring Data JPA, along with Hibernate 

library dependencies, as Hibernate is the most commonly used JPA implementation.


One more example, when we add the spring-boot-starter-web dependency, it will by default pull all the commonly used libraries while developing 

Spring MVC applications, such as spring-webmvc, jackson-json, validation-api, and tomcat. Not only does the spring-boot-starter-web add all these 

libraries but it also configures the commonly registered beans like DispatcherServlet, ResourceHandlers, MessageSource, etc. with sensible defaults.


Read more about starters on Important Spring Boot Starters with Examples

2. Spring Boot Autoconfiguration

Spring Boot provides automatic configuration for various components based on the classpath dependencies present in the project. It eliminates 

the need for manual configuration, reduces boilerplate code, and simplifies the setup process. 


For example, if you have the spring-webmvc dependency in your classpath, Spring Boot assumes you are trying to build a SpringMVC-based

web application and automatically tries to register DispatcherServlet if it is not already registered.

 

If you have any embedded database drivers in the classpath, such as H2 or HSQL, and if you haven’t configured a DataSource bean explicitly, 

then Spring Boot will automatically register a DataSource bean using in-memory database settings.


You will learn more about autoconfiguration at What is Spring Boot Auto Configuration?

3. Elegant Configuration Management

Spring Boot allows you to externalize configuration properties, such as database connection details, server port, and logging settings. 

It supports various configuration formats like properties files, YAML files, environment variables, and more. The externalized configuration

makes it easier to configure and manage application properties in different environments. 

4. Spring Boot Actuator

Spring Boot Actuator provides production-ready features out of the box. It allows developers to monitor and manage the application using 

built-in endpoints for health checks, metrics, logging, and more. Traditional Spring does not provide these features by default.


Read more about Spring Boot Actuator on Spring Boot Actuator

5. Easy-to-Use Embedded Servlet Container Support

Traditionally, while building web applications, you need to create a WAR file of your spring project and then deploy them on external 

servers like Tomcat, WildFly, etc. Spring Boot allows you to package your application as a standalone JAR file. 

It includes an embedded servlet container (Tomcat, Jetty, or Undertow) by default, making it easy to deploy and 

run applications without requiring an external server. 

==

40) What is an Actuator in Microservices? Why is it used?

Actuator is a sub-project of Spring Boot. It brings in production-ready features into an application and 

is mainly used to expose operational information about the running application's health, metrics, info, dump, env, etc. 

It uses HTTP endpoints or JMX beans to interact with it.


51) How can you balance the server-side load by utilizing Spring Cloud?

We can use the Netflix Zuul to balance the server-side load by utilizing Spring Cloud. It is also known as a JVM-based router.


53) What is the use of Netflix Hystrix?

Hystrix is an error tolerance and latency library. It is mainly used to isolate the access points. 

It also ensures that all 3rd party libraries and services are restricted. 

So, the application runs efficiently and avoids the kind of failures that occur in distributed systems.


5. Easy-to-Use Embedded Servlet Container Support

Traditionally, while building web applications, you need to create a WAR file of your spring project and then deploy them on external servers like 

Tomcat, WildFly, etc. Spring Boot allows you to package your application as a standalone JAR file. 

It includes an embedded servlet container (Tomcat, Jetty, or Undertow) by default, making it easy to deploy and 

run applications without requiring an external server. 

===

7. Explain @SpringBootApplication, @Configuration and @ComponentScan annotations

The @SpringBootApplication annotation indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration 

and component scanning. This is a convenience annotation that is equivalent to declaring below three annotations:

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan

@Configuration: The @Configuration annotation indicates that the class contains bean configurations and should be processed by the Spring IoC container. 

It allows you to define beans and their dependencies using annotations like @Bean.


@EnableAutoConfiguration: The @EnableAutoConfiguration annotation enables Spring Boot's auto-configuration mechanism. 

It automatically configures the Spring application based on the classpath dependencies, project settings, and environment. 

Auto-configuration eliminates the need for manual configuration and reduces boilerplate code.


@ComponentScan: The @ComponentScan annotation tells Spring where to look for components (such as controllers, services, and repositories) to be managed by 

the Spring IoC container. It scans the specified packages and registers the annotated classes as beans.

import org.springframework.boot.SpringApplication;  

import org.springframework.boot.autoconfigure.SpringBootApplication;  

@SpringBootApplication  

public class SpringBootExampleApplication   

{  

public static void main(String[] args)   

{  

SpringApplication.run(SpringBootExampleApplication.class, args);  

}  

}  


application.properties file, which for now only has one property:

server.port=8081

server.servlet.context-path=/springboot-webapp


Gradle : build.gradle or Maven : pom.xml

<parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <relativePath />

</parent>

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

    <groupId>com.h2database</groupId>

    <artifactId>h2</artifactId>

</dependency>


===

@RestController

@RequestMapping("/api/books")

@Autowired

@GetMapping

@GetMapping("/title/{bookTitle}")

@PostMapping

@ResponseStatus(HttpStatus.CREATED)

@DeleteMapping("/{id}")

@RequestBody

@ResponseBody 

==

 @ExceptionHandler({ BookNotFoundException.class })

    protected ResponseEntity<Object> handleNotFound(

      Exception ex, WebRequest request) {

        return handleExceptionInternal(ex, "Book not found", 

          new HttpHeaders(), HttpStatus.NOT_FOUND, request);

    }

==

8. What are Spring boot starters and name a few important Spring boot starter dependencies?

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop 

for all the Spring and related technology that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors.

 

For example, while developing the REST service or web application; we can use libraries like Spring MVC, Tomcat, 

and Jackson – a lot of dependencies for a single application. The spring-boot-starter-web starter can help to reduce the number of manually added dependencies 

just by adding a spring-boot-starter-web dependency.

 

So instead of manually specifying the dependencies just add one spring-boot-starter-web starter to your spring boot

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

Few commonly used Spring boot starters:

spring-boot-starter: core starter, including auto-configuration support, logging, and YAML

spring-boot-starter-aop: for aspect-oriented programming with Spring AOP and AspectJ

spring-boot-starter-data-jpa: for using Spring Data JPA with Hibernate

spring-boot-starter-security: for using Spring Security

spring-boot-starter-test: for testing Spring Boot applications

spring-boot-starter-web: for building web, including RESTful, applications using Spring MVC.

spring-boot-starter-data-mongodb: Starter for using MongoDB document-oriented database and Spring Data MongoDB

spring-boot-starter-data-rest: Starter for exposing Spring Data repositories over REST using Spring Data REST

spring-boot-starter-webflux: Starter for building WebFlux applications using Spring Framework’s Reactive Web support

==

9. How does Spring Enable Creating Production-Ready Applications in a Quick Time?

Spring Boot aims to enable production-ready applications in a quick time. Spring Boot provides a few non-functional features out of the box like 

caching, logging, monitoring, and embedded servers.

spring-boot-starter-actuator - To use advanced features like monitoring & tracing to your application out of the box

spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat - To pick your specific choice of Embedded Servlet Container

spring-boot-starter-logging - For Logging using log back

spring-boot-starter-cache - Enabling Spring Framework’s caching support

==

15. What is the Spring Boot Actuator and its Features?

Spring Boot Actuator provides production-ready features for monitoring and managing Spring Boot applications. 

It offers a set of built-in endpoints and metrics that allow you to gather valuable insights into the health, performance, and management of your application.


Here are some key features provided by Spring Boot Actuator:

Health Monitoring: The actuator exposes a /health endpoint that provides information about the health status of your application. 

It can indicate whether your application is up and running, any potential issues, and detailed health checks for different components, 

such as the database, cache, and message brokers.


Metrics Collection: The actuator collects various metrics about your application's performance and resource utilization. 

It exposes endpoints like /metrics and /prometheus to retrieve information about HTTP request counts, memory usage, 

thread pool statistics, database connection pool usage, and more. These metrics can be integrated 

with monitoring systems like Prometheus, Graphite, or Micrometer.


Auditing and Tracing: Actuator allows you to track and monitor the activities happening within your application. 

It provides an /auditevents endpoint to view audit events like login attempts, database changes, or any custom events. 

Additionally, Actuator integrates with distributed tracing systems like Zipkin or Spring Cloud Sleuth to trace requests 

as they flow through different components.


Environment Information: The actuator exposes an /info endpoint that displays general information about your application, 

such as version numbers, build details, and any custom information you want to include. It is useful for providing diagnostic 

details about your application in runtime environments.


Configuration Management: Actuator provides an /configprops endpoint that lists all the configuration properties used in your application. 

It helps in understanding the current configuration state and identifying potential issues or inconsistencies.


Remote Management: Actuator allows you to manage and interact with your application remotely. It provides various endpoints, 

such as /shutdown to gracefully shut down the application, /restart to restart the application, and /actuator to list all available endpoints. 

These endpoints can be secured using Spring Security for proper access control.


Enabling the Actuator: The simplest way to enable the features is to add a dependency to the spring-boot-starter-actuator dependency. 

 <dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-actuator</artifactId>

 </dependency>

For Gradle, use the following declaration:

dependencies {

    compile("org.springframework.boot:spring-boot-starter-actuator")

}

===

16. How to Use Jetty Instead of Tomcat in Spring-Boot-Starter-Web?

To use Jetty instead of Tomcat in spring-boot-starter-web: 

Exclude Tomcat from the spring-boot-starter-web dependency. 

Add the spring-boot-starter-jetty dependency. 

Here's a Maven example:

<!-- Spring Boot Web Starter with Tomcat excluded -->

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

    <exclusions>

        <exclusion>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-tomcat</artifactId>

        </exclusion>

    </exclusions>

</dependency>


<!-- Add Spring Boot Jetty Starter -->

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-jetty</artifactId>

</dependency>

Once these changes are made, Spring Boot will automatically use Jetty as the embedded server when the application starts.

==

17. How to generate a WAR file with Spring Boot?

I suggest below three steps to generate and deploy the Spring Boot WAR file.

Set the packaging type to war in Maven build tool:

<packaging>war</packaging>

==

18. How many types of projects we can create using Spring Boot?

We can create 3 types of projects using Spring boot starter dependencies.


3 types of Spring boot applications:

If we have a spring-boot-starter dependency in a classpath then the spring boot application comes under the default category.

If we have spring-boot-starter-web dependency in a classpath then the spring boot application comes under the servlet category.

If we have a spring-boot-starter-webflux dependency in a classpath then the spring boot application comes under the reactive category.

==

21. How to use logging with Spring Boot?

We can use logging with Spring Boot by specifying log levels on the application.properties file. 

Spring Boot loads this file when it exists in the classpath and it can be used to configure both Spring Boot and application code.

Spring Boot, by default, includes spring-boot-starter-logging as a transitive dependency for the spring-boot-starter module. 

By default, Spring Boot includes SLF4J along with Logback implementations.

If Logback is available, Spring Boot will choose it as the logging handler. You can easily configure logging levels 

within the application.properties file without having to create logging provider-specific configuration files such as logback.xml or log4j.properties.

logging.level.org.springframework.web=INFO

logging.level.org.hibernate=ERROR

logging.level.net.guides=DEBUG

==

22. What is the Spring Boot Starter Parent and How to Use it?

All Spring Boot projects typically use spring-boot-starter-parent as the parent in pom.xml.

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.0.4.RELEASE</version>

    </parent>

spring-boot-starter-parent allows us to manage the following things for multiple child projects and modules:

Configuration - Java Version and Other Properties

Dependency Management - Version of dependencies

Default Plugin Configuration

We should need to specify only the Spring Boot version number on this dependency. 

If you import additional starters, you can safely omit the version number.

==

27. @RestController vs @Controller in Spring Boot?

Here are the key points on the difference between @RestController and @Controller for a quick interview response: 

Primary Purpose

@Controller: Primarily for traditional Spring MVC applications where methods return view names.


@RestController: Designed for RESTful services; methods return data directly to the client. 

Response Body

@Controller: Methods return view names. To send data as a response, you need to use @ResponseBody on the method. 


@RestController: Combines @Controller and @ResponseBody, so methods return data by default.

Content Negotiation

@Controller: Requires manual handling or @ResponseBody for automatic content negotiation.


@RestController: Automatic content negotiation and conversion (e.g., to JSON). 

Usage: 

@Controller: Suitable for serving web pages. 


@RestController: Ideal for creating RESTful web APIs. 


In summary, @Controller is used for web applications with views, while @RestController is used for REST APIs returning data directly.

28. @PathVariable vs @RequestParam in Spring

Here are the key differences between @PathVariable and @RequestParam in Spring, formatted for a quick interview response: 

Usage

@PathVariable: Extracts values from the URI path. 


@RequestParam: Extracts values from query parameters. 

URL Example

@PathVariable: /books/{id} -> /books/5 


@RequestParam: /books?bookId=5 

Declaration

@PathVariable: Used when a part of the URL itself is dynamic. 


@RequestParam: Used to extract values from the query string. 

Optional Values

@PathVariable: Assumes values are present (though you can set it as optional). 


@RequestParam: This can be optional or required. 

Default Values

@PathVariable: Does not support default values. 


@RequestParam: Supports default values using the defaultValue attribute. 

Use Case

@PathVariable: Suited for RESTful web services, where the URI is used to indicate resource hierarchy.


@RequestParam: Commonly used in form submissions and traditional web applications. 


In summary, @PathVariable extracts values from the URI path, while @RequestParam extracts values from query parameters.

==

2. What are the benefits of using Spring?

Spring targets to make Java EE development easier. Here are the advantages of using it:

Lightweight: Lightweight development with Java POJOs.

Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects

Aspect-Oriented Programming (AOP): Spring supports AOP to separate business logic from system services

IOC container: It is responsible for instantiating, configuring, and assembling the Spring beans by reading configuration metadata

MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses

Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by 

Spring Bean XML configuration file

Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions

==

3. What is Dependency Injection?

In simple terms, Dependency Injection an aspect of Inversion of Control (IoC), is a general concept stating that you do not create 

your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.

From Spring documentation - Dependency injection (DI) is a process whereby objects define their dependencies, that is, 

the other objects they work with, only through constructor arguments, arguments to a factory method, 

or properties that are set on the object instance after it is constructed or returned from a factory method. 

The container then injects those dependencies when it creates the bean. 

==

5. How can we inject beans in Spring?

Spring provides different options to inject beans:

Setter-based Injection

Constructor-based Injection

Field-based Injection

==

6. What is the Spring IOC container?

The Spring IOC container is responsible for instantiating, configuring, and assembling the Spring beans. 

The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. 

The configuration metadata is represented in XML, Java annotations, or Java code. 

It lets you express the objects that compose your application and the rich interdependencies between those objects.

The responsibilities of the IOC container are:

Instantiating the bean

Wiring the beans together

Configuring the beans

Managing the bean’s entire life-cycle

==

16. What are the types of Spring IOC containers?

Spring provides the following two distinct types of containers.

BeanFactory container

ApplicationContext container

==

9. How to Create a Spring Container?

Spring provides many ApplicationContext interface implementations that we use are;

AnnotationConfigApplicationContext: If we are using Spring in standalone Java applications and using annotations for Configuration, 

then we can use this to initialize the container and get the bean objects.

ClassPathXmlApplicationContext: If we have a spring bean configuration XML file in a standalone application, then we can use this class 

to load the file and get the container object.

FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the XML configuration file can be loaded 

from anywhere in the file system.

AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

Let's write a code to create a Spring container:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Note that we are supplying configuration metadata via the applicationContext.xml file(XML-based configuration).

AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);

Note that we are supplying configuration metadata via AppConfig.class file.

The most used API that implements the BeanFactory is the XmlBeanFactory.

 XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("applicationContext.xml"));

 ==

10. How to Retrieve Bean from Spring Container?

Both BeanFactory and ApplicationContext interface provides a getBean() method to retrieve bean from the spring container.

ApplicationContext getBean() Example:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

BeanFactory getBean() Example:

XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("beans.xml")); 

HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); 

==

12. When to Use Constructor-based and Setter-based DI in Spring?

From spring Framework documentation, since we can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for 

mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on 

a setter method can be used to make the property a required dependency.

Which of these DI methods is better purely depends on your scenario and some requirements. The following best practices may provide a guideline:

Use constructor-based DI for mandatory dependencies so that your bean is ready to use when it is first called. 

When your constructor gets stuffed with a large number of arguments, it's the figurative bad code smell. It's time to 

break your bean into smaller units for maintainability. 

Use setter-based DI only for optional dependencies or if you need to reinject dependencies later, perhaps using JMX. 

Avoid circular dependencies that occur when a dependency (say, bean B) of your bean (bean A) directly or indirectly depends on 

the same bean again (bean A), and all beans involved use constructor-based DI. You may use setter-based DI here. 

You can mix constructor-based and setter-based DI for the same bean, considering mandatory, optional, and circular dependencies. 

In a typical Spring application, you can see dependencies injected using both approaches, but this depends on the scenario, considering the preceding guidelines.

==

13. What is the difference between BeanFactory and ApplicationContext in the Spring framework?

One main between BeanFactory and ApplicationContext is that BeanFactory only instantiates bean when we call getBean() method while 

ApplicationContext instantiates singleton bean when the container is started, It doesn't wait for getBean() method to be called.

BeanFactory uses a lazy initialization approach whereas ApplicationContext uses an eager initialization approach.

BeanFactory:ApplicationContext

it supports only Singleton and Prototype bean scopes:It supports all types of bean scopes such as Singleton, Prototype, Request, Session etc.

This interface does not provides messaging (i18n or internationalization) functionality:ApplicationContext interface extends MessageSource interface, thus it provides messaging (i18n or internationalization) functionality.

BeanFactory does not support Event publication functionality.:Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface.



==

15. What is the default bean scope in the Spring framework?

By default, a Spring Bean is initialized as a singleton.

==

import java.io.*;

class Singleton {

    // static class

    private static Singleton instance;

    private Singleton()

    {

        System.out.println("Singleton is Instantiated.");

    }

    public static Singleton getInstance()

    {

        if (instance == null)

            instance = new Singleton();

        return instance;

    }

    public static void doSomething()

    {

        System.out.println("Somethong is Done.");

    }

}

 

class GFG {

    public static void main(String[] args)

    {

        Singleton.getInstance().doSomething();

    }

}

==

// Double Checked Locking based Java implementation of

// singleton design pattern

class Singleton {

    private static volatile Singleton obj = null;

    private Singleton() {}

 

    public static Singleton getInstance()

    {

        if (obj == null) {

            // To make thread safe

            synchronized (Singleton.class)

            {

                // check again as multiple threads

                // can reach above step

                if (obj == null)

                    obj = new Singleton();

            }

        }

        return obj;

    }

}

==

17. Are singleton beans thread-safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas singleton is a design pattern focusing on creation. 

Thread safety depends only on the bean implementation itself.

==

18. What are the different scopes of Spring Beans?

Spring Framework supports the following bean scopes :

singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container

prototype: Scopes a single bean definition to any number of object instances

request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is, 

each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext

session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext

application: Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext

WebSocket: Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

==

19. What Is Aspect-Oriented Programming (AOP)?

Aspect-oriented programming is a programming paradigm that tries to solve problems with cross-cutting concerns.

Aspect-oriented programming (AOP) complements object-oriented programming (OOP) by providing a different way to think about program structure.


Basically, enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and 

application modules, such as logging, transaction management, data validation, authentication, etc. In Object-Oriented Programming, 

the modularity of the application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and 

they are configured to cut across different class methods.


Logging

Security

Transaction management

Auditing,

Caching

Internationalization

Error detection and correction

Memory management

Performance monitoring

Synchronization

==

21. What are Aspect, Advice, Pointcut, JointPoint, and Advice Arguments in AOP?

Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. 

Aspects can be a normal class configured and then configured in the Spring Bean configuration file or we can use 

Spring AspectJ support to declare a class as Aspect using @Aspect annotation.


Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that get executed 

when a specific join point with a matching pointcut is reached in the application. You can think of Advice as

Spring interceptors or Servlet Filters.


Pointcut: Pointcut is regular expression that are matched with join points to determine whether advice needs to be executed or not. 

Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut 

expression language for determining the join points where advice methods will be applied.


JoinPoint: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. 

In Spring AOP a join point is always the execution of a method.


Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches 

the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined.

==

What is Response Entity in Spring-Boot?

In Spring Boot, a ResponseEntity is a class used to represent the entire HTTP response sent back to a client. It goes beyond just the data itself and encapsulates three key aspects:


Status Code: This indicates the outcome of the request, like success (200 OK), not found (404), or internal server error (500).

Headers: These are optional key-value pairs that provide additional information about the response, such as content type, cache control, or authentication details.

Body: This is the actual data being sent back to the client. It can be anything from JSON or XML to plain text, depending on your API design.

By using ResponseEntity, you gain fine-grained control over how Spring Boot constructs the response. You can set the appropriate status code, add custom headers, and include the response data in the body. This allows you to build more informative and flexible APIs.


@RestController

public class ProductController {


    @GetMapping("/products/{id}")

    public ResponseEntity<Product> getProduct(@PathVariable Long id) {


        // Simulate product retrieval logic

        Product product = getProductFromDatabase(id);


        // Check if product exists

        if (product == null) {

            return ResponseEntity.notFound().build(); // 404 Not Found

        }


        // Return product with OK status (200)

        return ResponseEntity.ok(product);

    }


    // Simulate product retrieval from database (replace with your actual logic)

    private Product getProductFromDatabase(Long id) {

        // ... (implementation details)

        return new Product(id, "Sample Product", 10.0);

    }

}

How to configure multiple databases in spring-boot application?

This is very interesting question and gets repeated all the time in an interview.


Spring Boot offers a convenient way to configure multiple databases in your application. Here’s a breakdown of the steps involved:


1. Define Data Source Properties:


Spring Boot uses properties to configure data sources. You can define them in your application.yml or application.properties file.

Each data source needs its own set of properties, prefixed with a unique identifier. Common properties include:

url: Database connection URL.

username: Database username.

password: Database password.

driverClassName: JDBC driver class name for the database.

Here’s an example configuration for two databases named users and orders:


spring:

  datasource:

    users:

      url: jdbc:mysql://localhost:3306/users

      username: user

      password: password

      driverClassName: com.mysql.cj.jdbc.Driver

    orders:

      url: jdbc:postgresql://localhost:5432/orders

      username: orders_user

      password: orders_password

      driverClassName: org.postgresql.Driver

2. Create DataSource Beans:


Spring Boot provides annotations and utilities to create DataSource beans.

You can use @ConfigurationProperties to map the data source properties defined earlier to a bean.

Here’s an example configuration class with DataSourceBuilder to create beans for each data source:

@Configuration

public class DataSourceConfig {


  @Bean

  @ConfigurationProperties(prefix = "spring.datasource.users")

  public DataSource usersDataSource() {

    return DataSourceBuilder.create().build();

  }


  @Bean

  @ConfigurationProperties(prefix = "spring.datasource.orders")

  public DataSource ordersDataSource() {

    return DataSourceBuilder.create().build();

  }

}

Configure Entity Manager and Transaction Manager (Optional):


If you’re using Spring Data JPA, you’ll need to configure separate Entity Managers and Transaction Managers for each data source.

These can be created similarly to DataSource beans, specifying the entities associated with each data source.

4. Injecting the Correct DataSource:


By default, Spring Boot auto-configures a single DataSource. To use specific data sources:

You can inject @Qualifier("usersDataSource") or @Qualifier("ordersDataSource") for specific repositories or services.

JPA repositories can also use @Entity annotation with a entityManagerFactoryRef attribute to specify the EntityManager.

Remember to adapt the configuration details (database type, connection details) to your specific databases.


How to declare Global Exceptions in Springboot application?[imp question]

Spring Boot offers two main approaches to declare Global Exceptions:


1. Using @ControllerAdvice:


This is the recommended approach for centralized exception handling. Here’s how it works:


Create a class annotated with @ControllerAdvice.

Define methods annotated with @ExceptionHandler to handle specific exceptions.

These methods can:

Return a custom error response object containing details about the exception.

Set a specific HTTP status code using ResponseEntity.

Log the exception for further analysis.

@ControllerAdvice

public class GlobalExceptionHandler {


  @ExceptionHandler(ResourceNotFoundException.class)

  public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {

    ErrorResponse errorResponse = new ErrorResponse("Resource not found");

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);

  }


  // Define methods for other exceptions you want to handle globally

}

===

Circuit Breaker: Hystrix

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture, it is common to have multiple layers of service calls, as shown in the following example:

A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service exceed circuitBreaker.requestVolumeThreshold (default: 20 requests) and the failure percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit, a fallback can be provided by the developer.


@SpringBootApplication

@EnableHystrixDashboard

@EnableCircuitBreaker

public class Application {


    public static void main(String[] args) {

        new SpringApplicationBuilder(Application.class).web(true).run(args);

    }


}


@Component

public class StoreIntegration {


    @HystrixCommand(fallbackMethod = "defaultStores")

    public Object getStores(Map<String, Object> parameters) {

        //do stuff that might fail

    }


    public Object defaultStores(Map<String, Object> parameters) {

        return /* something useful */;

    }

}

===

API Gateway:


API Gateway Capabilities

API gateways commonly implement capabilities that include:

Security policy – Authentication, authorization, access control, and encryption

Routing policy – Routing, rate limiting, request/response manipulation, circuit breaker, blue-green and canary deployments, A/B testing, load balancing, health checks, and custom error handling

Observability policy – Real-time and historical metrics, logging, and tracing

For additional app- and API-level security, API gateways can be augmented with web application firewall (WAF) and denial of service (DoS) protection.


API Gateway Benefits

Deploying an API gateway for app delivery can help:


Reduce complexity and speed up app releases by encapsulating the internal application architecture and providing APIs tailored for each client type

Streamline and simplify request processing and policy enforcement by centralizing the point of control and offloading non-functional requirements to the infrastructure layer

Simplify troubleshooting with granular real-time and historical metrics and dashboards

API Gateway and Microservices Architecture

For microservices‑based applications, an API gateway acts as a single point of entry into the system. It sits in front of the microservices and simplifies both the client implementations and the microservices app by decoupling the complexity of an app from its clients.


In a microservices architecture, the API gateway is responsible for request routing, composition, and policy enforcement. It handles some requests by simply routing them to the appropriate backend service, and handles others by invoking multiple backend services and aggregating the results.


An API gateway might provide other capabilities for microservices such as authentication, authorization, monitoring, load balancing, and response handling, offloading implementation of non-functional requirements to the infrastructure layer and helping developers to focus on core business logic, speeding up app releases.


Learn more about Building Microservices Using an API Gateway on our blog.

server:

  port: 8085

spring:

  application:

    name: API-GATEWAY-SERVICE

  cloud:

    gateway:

      routes:

        - id: DEMO-SERVICE

          uri: http://localhost:9090

          predicates:

            - Path=/demo/**


package com.gfg.demo.controller; 

  

import org.springframework.http.ResponseEntity; 

import org.springframework.web.bind.annotation.GetMapping; 

import org.springframework.web.bind.annotation.RequestMapping; 

import org.springframework.web.bind.annotation.RestController; 

  

@RestController

@RequestMapping("/demo") 

public class DemoController { 

  

    @GetMapping("/gfg") 

    public ResponseEntity<String> getAnonymous() { 

        return ResponseEntity.ok("Welcome to GeeksforGeeks"); 

    } 

  

}

===

SpringBoot : @Async : Simply put, annotating a method of a bean with @Async will execute it in a separate thread. In other words, the caller will not wait to complete the called method. One interesting aspect of Spring is that the event support in the framework also has support for async processing if necessary.

The method must be public.

===

Stereotype Annotations

Spring Framework provides us with some special annotations. These annotations are used to create Spring beans automatically in the application context. 

@Component annotation is the main Stereotype Annotation. There are some Stereotype meta-annotations which is derived from @Component those are

@Component: is base annotation for below annotations

@Service: holding the business logic.

@Repository: indicate that they’re dealing with CRUD operations, usually, it’s used with DAO (Data Access Object) or Repository implementations that deal with database tables.

@Controller:front controllers and responsible to handle user requests and return the appropriate response.

====

Read properties or messages from properties files.

Ex: 

employee.properties file has emp.name=sre


@Configuration

@PropertySource("classpath:employee.properties")

public class Application {


    @Value("${emp.name}")

    private String empName;


    //...

}

---

if emp.name=sre is there in application.properties then @PropertySource is not required, spring considers to fetch from application.properties 

====

@ConfigurationProperties: allows the developer to map the entire content of the properties file to a POJO (Plain Old Java Object).

Below example @ConfigurationProperties binds data from global.properties to ConfigProperties.java


global.properties

mail.from = t1@t1.com

mail.to = t2@t2.com

mail.port = 8080


@Configuration

@PropertySource("classpath:global.properties")

@ConfigurationProperties(prefix = "mail")

public class ConfigProperties {

        

    private String from;

    private String to;

    private int port;


    // standard getters and setters

}

===

@Profiles:provide a way to segregate parts of your application configuration and make it only available in certain environments ( dev / tst /  / prd / .. )


@Component

@Profile("dev")

public class DevDatasourceConfig


application.properties:

spring.profiles.active=dev


application-dev.properties has url, un, pwd, driver, port, or configurations

application-tst.properties has url, un, pwd, driver, port, or configurations

application-prd.properties has url, un, pwd, driver, port, or configurations


Alternatively, we could access the profiles by injecting the property spring.profiles.active:

@Value("${spring.profiles.active}")

private String activeProfile;


The profile names can also be passed in via a JVM system parameter. These profiles will be activated during application startup:

-Dspring.profiles.active=dev


dev env congiguration executes

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

@Scope("***"):

The scope of a bean defines the life cycle and visibility of that bean in the contexts we use it.

The latest version of the Spring framework defines 6 types of scopes:


singleton

prototype

request

session

application

websocket


@Component

@Scope("singleton")

public class MyBean {

   ===

   ===

}

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

@RestControllerAdvice @ExceptionHandler: Exception handling can be done with @RestControllerAdvice @ExceptionHandler

---

@RestController

@RequestMapping("/customer")

public class CustomerController {


    @Autowired

    private CustomerManager customerManager;


    @GetMapping("/{id}")

    public Customer getCustomer(@PathVariable String id) {

        return customerManager.getCustomer(id).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));

    }

}

---

one class can handle multiple execeptions.


@RestControllerAdvice

public class ExceptionAdvice {


    @ExceptionHandler(value = NotFoundException.class)

    public ResponseEntity<CustomErrorResponse> handleGenericNotFoundException(NotFoundException e) {

        CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR", e.getMessage());

        error.setTimestamp(LocalDateTime.now());

        error.setStatus((HttpStatus.NOT_FOUND.value()));

        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);

    }  


    @ExceptionHandler(Exception.class)

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)

    public ErrorMessage globalExceptionHandler(Exception ex, WebRequest request) {

        ErrorMessage message = new ErrorMessage(

        HttpStatus.INTERNAL_SERVER_ERROR.value(),

        new Date(),

        ex.getMessage(),

        request.getDescription(false));

        return message;

  }

}

---

{

  "errorCode": "NOT_FOUND_ERROR",

  "errorMsg": "Customer not found with id 1",

  "status": 404,

  "timestamp": "2019-12-26 11:45:59"

}

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

Hibernate: ACID - Automicity-either commit or rollback, Consistency-data has consist like money debit and credit that properly done , Isolation-tasks has to be done isolately , Durability-once transaction is done data has to be durable

===

Spring Cloud – Client Side Load Balancing with Ribbon

Ribbon is a particular load balancer given by Netflix you don’t have to write any code to develop this load balancer or to make this pattern happens. We can simply use the Netflix Ribbon to have the client-side load balancing. So, in this article, we are going to see how Netflix’s Ribbon helping us with client-side load balancing in Spring Boot.


@FeignClient(name = "address-service", path = "/address-service")

@RibbonClient(name = "address-service")

public interface AddressClient {


    @GetMapping("/address/{id}")

    public ResponseEntity<AddressResponse> getAddressByEmployeeId(@PathVariable("id") int id);


}


Make the following changes in your application.properties file.

address-service.ribbon.listOfServers=http://localhost:8081, http://localhost:8082

-----

Server-Side Load Balancer Provided by Spring Cloud: Spring Cloud Gateway, Netflix Zuul

=========

Request and response need to be xml:

    @PostMapping(path = "/members", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)

    public User echoXmlUser(@RequestBody User user) {

        return user;

    }

--

@PostMapping(path = "/members", consumes = ""application/xml", "text/xml", produces = { "application/xml", "text/xml" })) 

public void function1(@RequestBody Datatype variable) { 

  

--

@PostMapping(path = "/members", 

        consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, 

        produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }

)

====