0% found this document useful (0 votes)
112 views

Spring Boot Basics

Spring boot basics

Uploaded by

abdul Muqtadir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

Spring Boot Basics

Spring boot basics

Uploaded by

abdul Muqtadir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Spring Boot is an open source Java-based spring framework, which ease to develop a stand-alone and

production ready micro service-based applications:

Spring boot is a combination of spring framework, embedded HTTP servers and configuration annotation

It follows “Opinionated Defaults Configuration” Approach to avoid lot of boilerplate code and configuration to
improve Development, Unit Test and Integration Test Process.

Spring boot reduce Development, Unit Test and Integration Test time and to ease the development of
Production ready web applications.

Spring boot comes with auto configuration, for instance, we must mention the dependency it will configure the
spring boot accordingly, just we need to add the @EnableAutoConfiguration annotation

Spring boot support both Java and Groovy.

Spring boot also support Spring Initializer to generate the base project.

@SpringBootApplication annotation requires to configure the spring boot application.

Spring boot embedded HTTP server generally run on 8081 server port.

Spring boot ease and simplify the development of rest full web service and provide a quicker development
technique by using the key features provided by spring boot framework.

DIFFERENCE:

Sure, I can explain the differences between Spring and Spring Boot point by point:

1. Purpose:

Spring: Spring is a comprehensive framework that provides support for developing Java applications, especially
enterprise-level applications. It covers a wide range of features, including dependency injection, data access,
security, transaction management, and more.
Spring Boot: Spring Boot is a part of the Spring Framework and is specifically designed to simplify the
bootstrapping and development of new Spring applications. It focuses on convention over configuration and
eliminates the need for setting up and configuring various components manually.
2. Configuration:

Spring: Spring applications require extensive configuration through XML files or Java annotations. Developers
need to configure various components like DataSource, EntityManagerFactory, etc., which can be complex and
time-consuming.
Spring Boot: Spring Boot applications use sensible defaults for configuration and provide a lot of auto-
configuration options. It minimizes the developer's effort by automatically configuring the application based on
the classpath settings, reducing the need for explicit configurations.
3. Dependency Management:

Spring: In regular Spring applications, developers need to manage dependencies manually, including specifying
versions and resolving conflicts. This can be challenging, especially in large projects with numerous
dependencies.
Spring Boot: Spring Boot simplifies dependency management by providing a set of starter templates. These
starters include pre-configured dependencies for specific tasks (e.g., web applications, data access) and
manage version compatibility. Developers can add starters to their project, and Spring Boot takes care of the
rest.
4. Embedded Servers:
Spring: In traditional Spring applications, developers need to deploy their applications in external servlet
containers like Apache Tomcat or Jetty.
Spring Boot: Spring Boot includes an embedded server (like Tomcat, Jetty, or Undertow) by default.
Applications can be run as standalone JAR files without the need for external servlet containers, simplifying
deployment and making it easier to create self-contained, executable JARs.
5. Production-Ready Features:

Spring: Spring provides various production-ready features, but developers need to configure them manually,
such as health checks, metrics, security, and externalized configuration.
Spring Boot: Spring Boot includes production-ready features out of the box. These features are auto-configured
and ready to use, allowing developers to focus on business logic rather than spending time on setting up
infrastructure-related concerns.
6. Development Time:

Spring: Developing applications with traditional Spring can be time-consuming due to the need for extensive
configuration and setup.
Spring Boot: Spring Boot significantly reduces development time by eliminating boilerplate code and
simplifying configuration. Developers can quickly bootstrap and prototype applications, focusing more on
business requirements.

Drawbacks:

Lack of control. The system creates a lot of unused dependencies, resulting in a large deployment file;
Hard to convert to. The process of converting a legacy or an existing Spring project to a Spring Boot application
can be complex and time-consuming;
Not suitable for large-scale projects. Many developers claim the tool is not suitable for building big monolithic
applications. Though some argue that it can handle large projects just fine, it’s far from a common consensus;
Can be inflexible. Spring Boot uses an opinionated approach. This means it gravitates towards a single solution
to any given issue. It reduces decision making in the coding process, but also makes it less flexible than that of
the parent framework.

How spring boot work internally?


Spring boot provides many abstraction layers to ease the development, underneath there are vital libraries
which work for us.

Using @EnableAutoConfigure annotation the spring boot application configures the spring boot application
automatically.
E.g. If you need MySQL DB in your project, but you haven’t configured any database connection, in that case,
Spring boot auto configures as in memory database.
The entry point of spring boot application is a class which contains @SpringBootApplication annotation and has
the main method.
Spring boot scan all the components included in the project by using @ComponentScan annotation.
Let’s say we need the Spring and JPA for database connection, then we no need to add the individual
dependency we can simply add the spring-boot-starter-data-jpa in the project.
Spring boot follows the naming convention for dependency like spring-boot-starter.
Considering above there are other internal functions which play a significant role in spring boot.

What is the important dependency of spring boot application?

Below are the key dependencies which you need to add in maven based or Gradle based applications, to make
the application compatible to use spring boot functionality.

spring-boot-starter-parent
spring-boot-starter-web
spring-boot-starter-actuator
spring-boot-starter-security
spring-boot-starter-test
spring-boot-maven-plugin
These dependencies come with associated child dependencies, which are also downloaded as a part of parent
dependencies.

A must-know for anyone heading into Spring Boot interview, this question is frequently asked in Java Spring
Boot interview questions.

What are the basic components of spring boot?


Below is the basic component, which plays a vital role in spring boot framework for configuration,
development, deployment, and execution of microservices based application.

Spring boot starter.


Spring boot auto configurator.
Spring boot actuator.
Spring boot CLI.
Spring boot Initilizr.

What is an auto-configuration?

Spring boot autoconfiguration, check what are the jars that are available in the classpath, according to that
autoconfiguration provides a basic configuration to the application according to that jars or library available.

Spring Boot autoconfigurator is used by Spring Boot Framework to provide “Auto-Configuration”.


Auto-configuration solves the problem of doing amount of configuration in Spring framework, it detects the
dependency in a pom.xml file and according to that it configures the spring boot application.
Below is the key annotation which we need to use to enable autoconfiguration
@EnableAutoConfiguration

We have a below option to enable the specific class to autoconfigure with the existing application.
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

If we need to enable the external properties file, we can use the below annotation.
@EnableConfigurationProperties(MySQLDataSourceProperties.class)

Below annotation works when there is no bean available in the class path than its configure with configure
bean class.
@ConditionalOnMissingBean

Spring boot autoconfigurationSpring boot autoconfiguration brings certain level of intelligence into the
application so that it removes the hurdles to provide the configuration manually. One can debug the spring
boot application by using the below approach:
Switch on the debug logging
Trigger the spring boot actuator

What is a Spring boot starter?

Spring boot starter comprises of templates which provide a Rapid Application Development, spring boot starter
contains a combination of all the relevant transitive dependencies.

Spring boot starter is a jar file which predominantly solves the auto-dependency resolution in a spring boot
application.
Spring boot starter follows the unified pattern, like every dependency start with spring-boot-starter-X, where X
will be the name of dependencies.
For instance, if we add the dependency like spring-boot-starter-web, the spring boot starter will internally
resolve and download all the associated dependencies, add to the application.
Spring boot also checks and resolves the transitive dependencies internally.
Below are some of the popular Spring boot starters:

Spring-boot-starter-web
Spring-boot-starter-mvc
Spring-boot-starter-security
Spring-boot-starter-jpa
Spring-boot-starter-tomcat
Spring-boot-starter-jetty
Spring-boot-starter-json

What is Spring boot CLI?

Spring boot CLI is a command line interface, which use and run test the microservices application based on
spring boot.

Spring Boot CLI is a module of Spring boot application which use to run and test Spring Boot applications from
the command prompt.
When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot
Autoconfiguration components to resolve all dependencies and execute the application.
Internally contains Groovy file which is a JAR Dependency Manager to add Spring Boot Defaults and resolve all
dependencies automatically.
Spring Boot CLI operation is a combination of below component:
Auto Dependency Resolution
Auto-Configuration
Management Endpoints
Embedded HTTP Servers

The benefits that we achieved from using spring boot CLI is, that we don’t need to use any import, no need to
do the xml configuration, no web.xml and no dispatcherservlet declaration and no need to create war file
manually.

What is a Spring-boot interceptor? Why do we need this features and is there any real use case scenario
where spring boot interceptor fits?

Spring boot interceptor is typically used to intercept the request and response call made by the UI and
microservices-based application, the need of this to add, filter, modified the information contain in request and
response.

Interceptor in Spring Boot one can use to add the request header before sending the request to the controller
Interceptor in Spring Boot can add the response header before sending the response to the client.
Spring boot works on the below technique.
Before sending the request to the controller
Before sending the response to the client
After completing the request and response.
The real-world use case of spring-boot interceptor is authentication and authorization, where we filter the
information from the request which contain the credential information which use to authenticate and other
information like role which require authorization.

What are the important annotation for Spring rest? What is the use case of this annotation?
@RestController: Define at class level, so that spring container will consider as RestENd point
@RequestMapping(value = "/products"): Define the REST URL for method level.
@PathVariable: Define as a method argument
@RequestBody: Define as a method argument
@ResponseEntity: To convert the domain object into the response format
@hasAuthority: To grant the access of corresponding endpoints
@GetMapping: To make endpoint compatible for get request.
@PostMapping: To make endpoint compatible for post request.
@PutMapping: To make endpoint compatible for put request.
@DeleteMapping: To make endpoint compatible for delete request.
@ResponseStatus: To generate the HTTP status.
@ResponseBody: To Generate the response message.

Is it possible to have a Spring Boot Application without using @SpringBootApplication annotation? If yes,
explain why would you do that?

@SpringBootApplication annotation is not mandatory, it is possible to have a Spring boot based application
without using it.

You will do that when you don’t want to go with implicit features provided by @SpringBootApplication
annotation.

SpringBootApplication annotation is defined as :

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM,
classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
Let’s say you don’t want to use component scan in your application but would like to go with enabling feature
that executes the code for dependencies with default configuration (@EnableAutoConfiguration)

You can probably define your class as :

@Configuration
@EnableAutoConfiguration
@Import({ MyConfiguration1.class, MyConfiguration2.class,MyConfiguration3.class })
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
Here MySpringBootApplication is Spring boot based Application however it does not go with component scan
instead it looks for specific configuration classes and import them to set up the configuration.

Another Application may use the following configuration :

@Configuration
@ComponentScan(basePackages = "com.example.demo.components")
public class MySpringBootApplication2 {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication2.class, args);
}
}
Here application wanted to avoid using @EnableAutoConfiguration however it still wanted to components can
feature hence MySpringBootApplication2 class definition includes that.

Can you explain Component Scanning in Spring Boot?

If you use @SpringBootApplication annotation, it brings in default Component scan which will scan the root or
base packages where your main class annotated with @SpringBootApplication is located and all its sub-
packages. It will also consider your main class as one of the configuration classes as it is annotated (implicitly)
with @Configuration ( This is included by @SpringBootApplication annotation).

This is equivalent to the following definition :

@Configuration
@ComponentScan
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
Typically, in your application, you may want to limit the component scan to certain packages. You can achieve
that by specifying the base package, for example,

@ComponentScan("com.example.demo.myapp")
This will scan for all Spring components inside com.example.demo.myapp package ( When we say Spring
Components we mean Classes annotated with @Service, @Component, @Repository & @Controller etc.)

If you would like to scan multiple packages, it would be :

@ComponentScan({"com.example.demo.myapp1",”com.example.demo.myapp2”})
Type-safe alternative would be :

@ComponentScan(basePackageClasses = {com.example.demo.myapp1.Example1.class,
com.example.demo.myapp2.Example2.class})
Here Example1.class acts as a marker class for package com.example.demo.myapp1 , when you specify this
class , it will scan all other classes from the package com.example.demo.myapp1 along with Exmaple1.class.
Similar is the case for myapp2 package.

@ComponentScan(basePackages = "com.mypackage",
includeFilters = @Filter(type = FilterType.REGEX, pattern="com.mypackage.*.*subpackage"),
excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = NotToBeScannedClass.class))
Here Regex FilterType is used for inclusion which means any class whose package matches the pattern
(com.mypackage.*.*subpackage) will be included in the scan while using AssignableType Filter, we have
specified that a particular class should not be included in scanning.

@ComponentScan(basePackages = "com.mypackage",
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes =
MyCustomAnnotation.class)})
MyAnnotation is defined as :

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}
Here any class that is annotated with MyCustomAnnotation annotation will be included in the scan
What is a Spring Boot Actuator? What are the features provided and how you can customize or add more?

The actuator provides built-in features to your application which are production-ready. It provides web
endpoints for each of this feature. Some of the most common Spring Boot Actuator endpoints:

/health: It shows application health information.


/info: It shows arbitrary application info.
/metrics: It shows all metrics related information for the current application.
/trace: It shows trace information for last few HTTP requests.
/beans: It lists all Spring beans in your application.
/threaddump: Performs thread dump.
/env: Displays a list of properties in the current environment.
For example, when using MicroServices, you will definitely a health check for your microservice as your service
registry/Load Balancer need to be updated with only live or healthy services so that any incoming request to
your application goes to live node/server only. Instead of building your own health endpoint, you can just
import the Spring Boot Actuator and use the built-in health endpoint.

If you need to your own health endpoint, you can do so by implementing health() method from
org.springframework.boot.actuate.health.HealthIndicator.

To implement your own endpoint, you can implement org.springframework.boot.actuate.endpoint interface.

With Spring Boot Actuator 2.X, all endpoints except health and Info are disabled. To enable them you need to
set management.endpoints.web.exposure.include=*.

6) What is RAD model?


RAD or Rapid Application Development process is an adoption of the waterfall model; it targets developing
software in a short period. RAD follow the iterative

SDLC RAD model has the following phases:

Business Modeling
Data Modeling
Process Modeling
Application Generation
Testing and Turnover

What is the purpose of @RestController annotation?

In Spring Framework, specifically in the context of Spring MVC, the @RestController annotation is a specialized
version of the @Controller annotation. It is used to define a class as a RESTful web service controller.

When you annotate a class with @RestController, it combines the @Controller and @ResponseBody
annotations. This means that methods in the class, by default, return data serialized as JSON (or XML if
configured) directly to the body of the HTTP response. In other words, the return values of the methods in a
@RestController are directly written to the HTTP response body as a JSON or XML (or other supported formats)
response.

What is the purpose of @ResponseBody Annotation?


In Spring Framework, the @ResponseBody annotation is used to indicate that the return value of a method
should be bound to the web response body. It is commonly used in Spring MVC controllers to handle RESTful
web services, where the response data is sent directly to the client as the body of the HTTP response, rather
than being rendered into a view such as an HTML template.

When you annotate a method with @ResponseBody, Spring Framework will convert the return value of the
method to a suitable format for the HTTP response body. This conversion is typically done using an appropriate
HttpMessageConverter. For example, if you return a Java object from a method annotated with
@ResponseBody, Spring will use a JSON converter to convert the object to JSON format and include it in the
response body.
In this example, the getData() method returns a MyData object, and the @ResponseBody annotation ensures
that this object will be converted to the appropriate response format (e.g., JSON) and sent in the response
body when the client makes a GET request to the /data endpoint.

What is the purpose of @Controller annotation?


In the context of Spring Framework for Java, the @Controller annotation is used to indicate that a class serves
the role of a controller in a Spring MVC (Model-View-Controller) application. Controllers are responsible for
processing incoming requests, performing operations on the data model, and returning the appropriate view to
the client.

When you annotate a class with @Controller, Spring automatically detects it during the component scanning
process and registers it as a controller in the Spring application context. This allows the Spring framework to
identify the class as a controller and handle the incoming HTTP requests.

Spring Boot Annotations Everyone Should Know


1. @Bean
The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be
managed by the Spring container. It is an alternative to the XML<bean> tag.

Example:

@Bean

Public BeanExample beanExample ()

return new BeanExample (),

In the spring boot annotation, beans are the objects that are the backbone of the application and are managed
by the Spring IoC container. The Spring Bean annotation is declared in the configuration classes 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.
3. @Repository
It is a Data Access Object (DAO) that accesses the database directly. It indicates that the annotated class is a
repository.
2. @Service
It is used at the class level. It shows that the annotated class is a service class, such as business basic logic, and
call external APIs.

Difference between Controller and Rest Controller annotation?


The @RestController annotation in Spring MVC is nothing but a combination of @Controller and
@ResponseBody annotation. It was added into Spring 4.0 to make the development of RESTful Web Services in
Spring framework easier. If you are familiar with the REST web services you know that the fundamental
difference between a web application and a REST API is that the response from a web application is generally
view (HTML + CSS + JavaScript) because they are intended for human viewers while REST API just returns data
in form of JSON or XML because most of the REST clients are programs. This difference is also obvious in the
@Controller and @RestController annotation.

@Component annotation?

The @Component annotation is a marker annotation that is part of the Spring Framework, which is widely used
for building enterprise-level applications. Specifically, @Component is used to indicate that a class is a Spring
component. Spring components are Java objects managed by the Spring IoC (Inversion of Control) container.

When you annotate a class with @Component, Spring automatically detects and registers this class during the
component scanning process. Component scanning is a way for Spring to automatically discover and register
Spring beans within your application context.

In the above example, the MyComponent class is annotated with @Component, which means it will be
automatically detected by Spring during component scanning and registered as a Spring bean.

Other annotations like @Service, @Repository, and @Controller are specialized forms of @Component. They
are used to indicate specific types of Spring components:

@Service is used to annotate classes that hold the business logic in a service layer.
@Repository is used to annotate classes that interact with databases or other data sources.
@Controller is used to annotate classes that handle web requests in a Spring MVC application.
All these annotations are meta-annotations of @Component, which means they ultimately have the same
effect as annotating a class with @Component. However, using these specialized annotations provides
additional semantic meaning to the reader and makes your code more expressive and self-documenting.

You might also like