Spring Interview Questions part-1
1.
Difference
between spring and spring boot.
Spring is one of the most widely used Java EE Frameworks for building applications. For the Java platform, the Spring framework provides an elaborate programming and configuration model. It aims to simplify Java EE development and helps developers be more productive at work. It can be used at any kind of deployment platform. It takes into account the rising needs of today’s businesses and strives to fulfill them.
Unlike other frameworks, Spring focuses on several areas of an application and provides a wide range of features.
One of the major features of the Spring framework is dependency injection. It helps make things simpler by allowing us to develop loosely coupled applications.
Spring Boot
While the Spring framework focuses on providing flexibility to you, Spring Boot aims to shorten the code length and provide you with the easiest way to develop a web application. With annotation configuration and default codes, Spring Boot shortens the time involved in developing an application. It helps create a stand-alone application with less or almost zero-configuration.
Autoconfiguration is a special feature in Spring Boot. It automatically configures a class based on that requirement.
2. Benefits of Spring framework.
The Spring Framework can be used for all layers of implementation in the development of an application.
· Considering its POJO model, it is a very lightweight framework.
· It allows loose coupling and easy testability.
· It supports declarative programming.
· It is capable of eliminating the formation of singleton and factory classes.
· It supports both XML and annotation configurations.
· It provides middleware services.
3. Despite having several in the Spring framework, what led to the emergence of Spring Boot?
Spring Boot helps in the easy usage of the Spring Framework by simplifying it to a great extent. Spring provides a loosely coupled application — this is a great feature. However, when there are several loosely coupled blocks, keeping track of them becomes a tedious and messy task. This is where Spring Block comes into the picture and helps simplify things by offering no configuration feature. It helps you get started with minimal effort and even provides externalized configuration.
4.Difference between Spring and Spring boot.
Spring Boot is a Spring-based production-ready project initializer. With features like auto-configuration, it saves you from writing lengthy code and helps you avoid unnecessary configuration.
While the Spring The framework offers you features like dependency injection or IOC and handles transactions, it also acts as a foundation for other Spring frameworks. The best example for this is Spring boot. Spring Boot uses the Spring Framework as a foundation and improvises on it. It simplifies Spring dependencies and runs applications straight from a command line. It also doesn’t require an application container. Spring Boot mostly helps in monitoring several components and configures them externally.
All in all, the Spring framework has made a significant contribution and continues to do so. With the many features mentioned above, the Spring framework is always a great choice for developers. However, it is highly beneficial when used alongside Spring Boot. The added advantages that come with Spring Boot are of great value to the developers as they offer completion of projects with minimal efforts. To all the problems that arise from the Spring framework, Spring Boot is the solution.
5.Benifits of Spring boot.
• Spring Boot doesn’t require you to deploy WAR files.
• It creates stand-alone applications.
• It helps embed Tomcat, Jetty, or Undertow directly.
• It doesn’t require XML configuration.
• It aims to reduce the LOC.
• It offers production ready features.
• It is easier to launch.
• Easier customization and management.
6. What is Inversion of Control (IOC)?
IoC is a design pattern that describes inverting the flow of control in a system, so execution flow is not controlled by a central piece of code. This means that components should only depend on abstractions of other components and are not be responsible for handling the creation of dependent objects. Instead, object instances are supplied at runtime by an IoC container through Dependency Injection (DI).
IoC enables better software design that facilitates reuse, loose coupling, and easy testing of software components.
7.What is Dependency Injection?
DI is a technique for passing dependencies into an object’s constructor. If the object has been loaded from the container, then its dependencies will be automatically supplied by the container. This allows you to consume a dependency without having to manually create an instance. This reduces coupling and gives you greater control over the lifetime of object instances.
8. Different @annotaions at spring and spring boot.
@Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at configuration time with the required property, else it throws an exception BeanInitilizationException.
@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching data-type.
@Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions.
@ComponentScan: It is used when we want to scan a package for beans. It is used with the annotation @Configuration. We can also specify the base packages to scan for Spring Components.
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be managed by Spring Container.
@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated with @Component is found during the classpath. The Spring Framework pick it up and configure it in the application context as a Spring Bean.
@Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation.
@Service: It is also used at class level. It tells the Spring that class contains the business logic.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database directly. The repository does all the operations related to the database.
@EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication.
@SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration.
@RequestMapping: It is used to map the web requests. It has many optional elements like consumes, header, method, name, params, path, produces, and value. We use it with the class as well as the method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint that fetches It is used instead of using: @RequestMapping(method = RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service endpoint that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint that creates or updates It is used instead of using: @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to create a web service endpoint that deletes a resource. It is used instead of using: @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used instead of using: @RequestMapping(method = RequestMethod.PATCH)
@RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it uses HTTP MessageConverters to convert the body of the request. When we annotate a method parameter with @RequestBody, the Spring framework binds the incoming HTTP request body to that parameter.
@ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL contains a path variable. We can define multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also known as a query parameter. It is most suitable for web applications. It can specify default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as a method parameter. The optional elements of the annotation are name, required, value, defaultValue. For each detail in the header, we should specify separate annotations. We can use it multiple time in a method
@RestController: It can be considered as a combination of @Controller and @ResponseBody annotations. The @RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
@RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the request attributes from a controller method. With the help of @RequestAttribute annotation, we can access objects that are populated on the server-side.
9. What is JPA how you used it in your spring boot application.
When you implement a new application, you should focus on the business logic instead of technical complexity and boilerplate code. That’s why the Java Persistence API (JPA) specification and Spring Data JPA are extremely popular. JPA handles most of the complexity of JDBC-based database access and object-relational mappings. On top of that, Spring Data JPA reduces the amount of boilerplate code required by JPA. That makes the implementation of your persistence layer easier and faster.
JPA is a specification that defines an API for object-relational mappings and for managing persistent objects. Hibernate and EclipseLink are 2 popular implementations of this specification. You can learn more about the difference in What’s the difference between JPA, Hibernate and EclipseLink
Spring Data JPA adds a layer on top of JPA. That means it uses all features defined by the JPA specification, especially the entity and association mappings, the entity lifecycle management, and JPA’s query capabilities. On top of that, Spring Data JPA adds its own features like a no-code implementation of the repository pattern and the creation of database queries from method names.
10. How you are handling Client-side session in spring application.
We can control exactly when our session gets created and how Spring Security will interact with it:
· always – a session will always be created if one doesn’t already exist
· ifRequired – a session will be created only if required (default)
· never – the framework will never create a session itself but it will use one if it already exists
· stateless – no session will be created or used by Spring Security
<http create-session="ifRequired">...</http>
or
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
}
By default, Spring Security will create a session when it needs one – this is “ifRequired“.
For a more stateless application, the “never” option will ensure that Spring Security itself will not create any session; however, if the application creates one, then Spring Security will make use of it.
Finally, the strictest session creation option – “stateless” – is a guarantee that the application will not create any session at all.
A bean can be defined with session scope simply by using the @Scope annotation on beans declared in the web-Context:
@Component
@Scope("session")
public class Foo { .. }
Or with XML:
<bean id="foo" scope="session"/>
Then, the bean can simply be injected into another bean:
@Autowired
private Foo theFoo;
11. What is actuators in spring boot.
Spring Boot Actuator is a sub-project of Spring Boot. It provides several production-grade services to your application out of the box. Once Actuator is configured in your Spring Boot application, you can interact and monitor your application by invoking different HTTP endpoints exposed by Spring Boot Actuator such as application health, bean details, version details, configurations, logger details, etc.
Spring Boot includes a number of built-in endpoints, and you can also add your own or even configure existing endpoints to be exposed on any custom endpoints of your choice. It is obvious that all the endpoints cannot be exposed publicly, considering that there are many sensitive endpoints like beans, env, etc. Hence, Spring Boot also sets sensitive defaults to true for many endpoints that require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled). Health and info are not sensitive by default.
12. How do you write userCreation service in spring boot.
13.Different HTTP methods used in Spring Boot(i.e: @GetMapping,@DeleteMapping,@PostMapping,@PatchMapping,@PutMapping)
Below is the list of method that used while creating your RESTful API.
1. GET
2. POST
3. PUT
4. DELETE
5. PATCH
1. GET Method
HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same.
2. POST Method
This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care.
3. PUT Method
If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind
· PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time)
4. DELETE Method
DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the system and it should return 404 response.DELETE can be a long-running or asynchronous request.
5. PATCH Method
Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method.
· Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges.
· Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents.
14. What is GetMapping,DeleteMapping,PostMapping,PatchMapping,PutMapping
@GetMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET). @GetMapping annotated methods handle the HTTP GETrequests matched with given URI expression
@DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).
@PostMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST). @PostMapping annotated methods handle the HTTP POST requests matched with given URI expression
@PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).
@PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).
15. Difference between Put and Post methods
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
16. Difference between Post, Put and Patch methods
POST
You use POST to create a resource and instruct the server to make a Uniform Resource Identifier (URI) for it. For example, when you want to create a new article you would POST to /articles to make the file and get the URI, so you end up with /articles/1234/.
PUT
PUT also creates resources, but it does so for a known URI. So, you can PUT to /articles/1234/. If the article doesn't exist, PUT creates it. If it does exist, this HTTP verb updates it. While PUT seems nearly identical to POST, the difference between the two comes down to idempotence.
Idempotence is a property that creates identical side effects whether you have one or many results. PUT has this characteristic, while POST creates new resources infinitely. In general, POST works best for resource creation, while PUT handles updates.
PATCH
So, where does PATCH come into the picture? This HTTP verb partially updates resources without sending the complete representation of it. When you're working with complicated objects and resources, it's a big deal to update more than you need to.
16. What is the use of @Configuration in spring.
Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.
@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning (typically using Spring XML's <context:component-scan/> element) and therefore may also take advantage of @Autowired/@Inject like any regular @Component. In particular, if a single constructor is present autowiring semantics will be applied transparently for that constructor:
17. Different annotations in Spring Boot, like @repository, @service, @RestController, @RequestMapping.
@Repository Annotation
Although above use of @Component is good enough but we can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.
@Service Annotation
The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.
@RestController
This annotation was introduced in Spring 4.0 to simplify the creation of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody – which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.
@RequestMapping
This is one of the most common annotations used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.
18. What is OAUTH?
OAuth is an open standard authorization protocol or framework that describes how unrelated servers and services can safely allow authenticated access to their assets without actually sharing the initial, related, single logon credential. In authentication parlance, this is known as secure, third-party, user-agent, delegated authorization.
19. What is Restful API - stateless and state-full services?
A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.
A RESTful API -- also referred to as a RESTful web service -- is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.
A stateless system can be seen as a box where at any point in time the value of the output(s) depends only on the value of the input(s)
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
20. What is two factor authentications?
Two-factor authentication (2FA), sometimes referred to as two-step verification or dual factor authentication, is a security process in which the user provides two different authentication factors to verify themselves to better protect both the user's credentials and the resources the user can access. Two-factor authentication provides a higher level of assurance than authentication methods that depend on single-factor authentication (SFA), in which the user provides only one factor -- typically a password or passcode. Two-factor authentication methods rely on users providing a password as well as a second factor, usually either a security token or a biometric factor like a fingerprint or facial scan.
Two-factor authentication adds an additional layer of security to the authentication process by making it harder for attackers to gain access to a person's devices or online accounts, because knowing the victim's password alone is not enough to pass the authentication check. Two-factor authentication has long been used to control access to sensitive systems and data, and online service providers are increasingly using 2FA to protect their users' credentials from being used by hackers who have stolen a password database or used phishing campaigns to obtain user passwords.