Spring and Spring boot Interview questions - Updated March 2022

what is spring-boot: a framework provided by spring, that helps to easily create a standalone, production-grade application.

recommended for building microservices
it provides an opinionated view of dependencies, for simplification of the build configuration.

REST is stateless: the client context is not stored on the server between requests, giving REST services the ability to be retried independently of one another.

How spring-boot works/working internally: From the run method, the main application context is kicked off which in turn searches for the classes annotated with @Configuration, initializes all the declared beans in those configuration classes, and based upon the scope of those beans, stores those beans in JVM, specifically in a space inside JVM which is known as IOC container. After the creation of all the beans, automatically configures the dispatcher servlet and registers the default handler mappings, messageConverts, and all other basic things.

run() -> internal flow
1. create application context
2. check application type
3. register the annotated class beans with the context
4. creates an instance of tomcat embedded servlet container and adds the context

spring boot supports three embedded servers:- Tomcat (default), Jetty and Undertow.

Autoconfiguration: Spring.factories all dynamic classes are there @onConditionBean etc

Circuit breaker- hystrix:
The Hystrix framework library helps to control the interaction between services by providing fault tolerance and latency tolerance. It improves the overall resilience of the system by isolating the failing services and stopping the cascading effect of failures.

uses the fallback method
dependency-> spring-cloud-starter-netflix-hystrix
when a microservice down an empty array will be thrown and once it is up and we hit the same microservice we will get the complete response

profiling/profiles: This is used to launch the same app in different envs using envs variables.
it is a configuration for multiple envs

port no=0: for default port assignment

Dispatcher servlet: DispatcherServlet acts as the front controller for Spring based web applications. It provides a mechanism for request processing where actual work is performed by configurable, delegate components.

Application context: is where all beans are created and managed.It represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. --> present in SpringAapplication class

IOC: Inversion of Control is a principle by which the control of objects or portions of a program is transferred to a container or framework. It's most often used in the context of object-oriented programming.

In the Spring framework, the IoC container is represented by the interface ApplicationContext. The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their lifecycle.

DI: Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of the object's dependencies.

Eureka: @EnableEurekaserver

zuul: zuul comes with a prepackaged load balancer called ribbon.it is router +  service side load balancer
@enablezuulproxy
@EnableEurekaClient -> to register zuul client with eureka server

h2:(hypersonic 2) db is used to test apps.it is in memory db

3 layers in spring boot:
1. presentation layer
2. service layer
3. data layer

dto -> data transfer object
impl- implementation

PATCH: method is a request method supported by the Hypertext Transfer Protocol (HTTP) protocol for making partial changes to an existing resource.

EntityManager:The purpose of the EntityManager is to interact with the persistence context. The persistence context will then manage entity instances and their associated lifecycle.
Spring Data JPA does an excellent job abstracting you from the EntityManager through its Repository interfaces-

Repository
CrudRepository
JPARepository
But occasionally, you need to access the EntityManager.

EntityManager.refresh
An example of this is the refresh method. The refresh method refreshes the state of an instance from the database and overwrites the copy held by the EntityManager. This ensures the EntityManager manager has the most up to date version of the data

Spring Boot Actuator: Spring Boot Actuator is a sub-project of the Spring Boot Framework. It includes a number of additional features that help us to monitor and manage the Spring Boot application. It contains the actuator endpoints (the place where the resources live). We can use HTTP and JMX endpoints to manage and monitor the Spring Boot application. If we want to get production-ready features in an application, we should use the Spring Boot actuator.
/health
/beans
/httptrace

Transaction management in spring:

1. Programmatic transaction management: This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
2. Declarative transaction management(recommended): This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
@EnableTransactionManagement
@Transactional
spring security:
What are CSRF (Cross-site request forgery) tokens:
A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client. When the later request is made, the server-side application validates that the request includes the expected token and rejects the request if the token is missing or invalid.

Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.

mocking: is creating objects that mimic the behavior of real objects.

Hibernate: is JPA provider
JpaRepository contains the full API of CrudRepository and PagingAndSortingRepository:
When we don't need the full functionality provided by JpaRepository and PagingAndSortingRepository, we can simply use the CrudRepository.

Anatomy of @SequenceGenerator:
The @SequenceGenerator annotation defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation.A sequence generator may be specified on the entity class or on the primary key field or property.

Target: Type, Method and Field
Uses:@SequenceGenerator
Argument:
name (Required): A unique generator name that can be referenced by one or more classes to be the generator for primary key values.
sequenceName (Optional): The name of the database sequence object from which to obtain primary key values.
initialValue (Optional): The value from which the sequence object is to start generating.
allocationSize (Optional): The amount to increment by when allocating sequence numbers from the sequence.
Hibernate.dialect : property tells Hibernate to generate the appropriate SQL statements for the chosen database.

Bean Scopes:
1. singleton : one instance per spring container
2. prototype : new instance created every time the bean is requested from the spring container.
3. request   : new instance of the bean will be created for each HTTP request.
4. session   : new bean will be created for each HTTP session by the container.
5. global-session : This is used to create global session beans for Portlet applications.

There are basically two types of IOC Containers in Spring:
BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.
ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface.

spring bean singleton scope vs gang of four singleton:
gang of four : 1 instance per classloader
singleton bean: 1 instance per container

Is the Singleton bean scope thread-safe- No :

make a spring bean thread-safe: - Thread safety is a different context . Singleton spring beans has no relation with thread safety. spring container only manages life-cycle of objects and guaranteed that only one object in spring container. @RequestScope
---------------------------------------------------------------------------------------------------------------------
Spring AOP: enables the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects 
---------------------------------------------------------------------------------------------------------------------
DispatcherServlet:The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.
In Spring MVC, all incoming requests go through a single servlet. This servlet - DispatcherServlet - is the front controller. Front controller is a typical design pattern in the web applications development. In this case, a single servlet receives all requests and transfers them to all other components of the application.
dispatcher servlet maps uris to different controller methods and gives response in form of json

The task of the DispatcherServlet is to send request to the specific Spring MVC controller.
----------------------------------------------------------------------------------------------------------------------------------------------------------
Pagination: in web applications is a mechanism to separate a big result set into smaller chunks. Providing a fluent pagination navigator could increase both the value of your website for search engines and enhance user experience through minimizing the response time. The famous example of pagination is Google's search result page. Normally, the result page is separated into several pages. To avoid the bad user experience mentioned before, a lot of sites show only the current, the first, the last, and some adjacent pages.

Static Pagination With Spring Data:
This is the most convenient way to implement pagination in a web application. It only needs to get the page and the number of result per page for a query.
PaginationAndSortingRepository:

Dynamic Pagination With a Native Query:This kind of pagination can be done with a native query in the Spring framework.you need to specify an offset row and a limit, which is the number of elements after this offset. You need also write your "page" class and map the response list to it.

----------------------------------------------------------------------------------------------------------------------------------------------------------
What is a Resource?:
REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.
----------------------------------------------------------------------------------------------------------------------------------------------------------
Spring Boot SSL/ Root certificate:

Spring boot HTTPS Config:
server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

Redirect from HTTP to HTTPS:
private Connector redirectConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(8080);
  connector.setSecure(false);
  connector.setRedirectPort(8443);
  return connector;
}

SSL: – stands for Secure Sockets Layer. It is the industry standard protocol for keeping an internet connection secure by safeguarding all sensitive data that is being sent between two systems, preventing hackers from reading and modifying any information transferred.

TLS: – (Transport Layer Security) is an updated, more secure, version of SSL. It adds more features. Today, certificates provided by certificate authorities are based on TLS only. But regarding secured communication over network, the term SSL is still common as it is the old and just become popular among community.

HTTPS: – (Hyper Text Transfer Protocol Secure) appears in the URL when a website is secured by an SSL certificate. It is the secured version of HTTP protocol.

Truststore and Keystore: – Those are used to store SSL certificates in Java but there is little difference between them. truststore is used to store public certificates while keystore is used to store private certificates of client or server.
----------------------------------------------------------------------------------------------------------------------------------------------------------
HTTP methods:
GET:The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
HEAD:The HEAD method asks for a response identical to that of a GET request, but without the response body.
POST:The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
PUT:The PUT method replaces all current representations of the target resource with the request payload.
DELETE:The DELETE method deletes the specified resource.
CONNECT:The CONNECT method establishes a tunnel to the server identified by the target resource.

OPTIONS:The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server.
        Syntax:
OPTIONS /index.html HTTP/1.1
OPTIONS * HTTP/1.1

TRACE:The TRACE method performs a message loop-back test along the path to the target resource.
PATCH:The PATCH method is used to apply partial modifications to a resource.
----------------------------------------------------------------------------------------------------------------------------------------------------------
enable http/2 in spring boot:
server.http2.enabled=true

default is http/1.1
----------------------------------------------------------------------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

Understanding and Avoiding Race Conditions in Java

The Interplay of Money and Risk

For Java