SpringBoot Flashcards

1
Q

What is a Spring boot?

A

Spring Boot is a tool that makes developing a web application and microservices with Spring Framework faster and easier through three core capabilities that are

Autoconfiguration
An opinionated approach to configuration
The ability to create standalone applications

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Purpose of Spring boot?

A

To avoid XML Configuration completely.
To avoid defining more Annotation Configurations.
To provide some defaults to quickly start new projects.
To provide an Opinionated Development approach.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Features of spring boot?

A

In-built starter projects.
In-built WebServers.
RestTemplate supports.
JSON Support.
Third-Party Integration Support.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why Spring Boot over Spring?

A

Actuators.
Version Management.
Auto Configuration.
Component Scanning.
Embedded server.
InMemory DB.
Starter POM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How the Spring boot application will use RestTemplate to test HTTP-based restful web services.

A

Spring RestTemplate class is part of spring-web, introduced in Spring 3. We can use RestTemplate to test HTTP-based restful web services, it doesn’t support the HTTPS protocol. RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE, etc. The Spring Framework 5, onwards we have the WebFlux stack, Spring introduced a new HTTP client called WebClient. It is an alternative HTTP client to RestTemplate. Not only does it provide a traditional synchronous API, but it also supports an efficient nonblocking and asynchronous approach.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a Spring boot Actuator?

A

Spring Boot Actuator is a component of the Spring Boot framework that offers features for monitoring and managing your application in production. It provides endpoints to retrieve information and perform operations on your application. Key features include health monitoring, metrics gathering, environment details, logging management, thread dumps, and endpoint customization. Actuator simplifies the monitoring and management process by providing out-of-the-box functionality and integration capabilities with other monitoring tools.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How we monitor and manage the Spring boot application.

A

To monitor and manage a Spring Boot application, you can use Spring Boot Actuator. It provides management endpoints that offer health checks, metrics, logging management, thread dumps, and more. You can access these endpoints over HTTP to monitor the application’s health, gather performance metrics, view environment details, manage logging, and analyze thread dumps. Actuator can be easily integrated into your Spring Boot application and customized according to your specific needs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How the Spring boot application will Auto-restart means reloading Java classes and configuring it on the server side, and loading the modified code.

A

DevTools stands for Developer Tool. The module aims to try and improve the development time while working with the Spring Boot application. Spring Boot DevTools pick up the changes and restart the application.

Automatic Restart: Auto-restart means reloading Java classes and configuring them on the server side. After the server-side changes, it is deployed dynamically, server restarts happen, and load the modified code.

LiveReload: The Spring Boot DevTools module includes an embedded server called LiveReload. It allows the application to automictically trigger a browser refresh whenever we make changes in the resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Here we will see what is spring boot environments, and how we can work with the same application but different configurations.

A

Spring Boot allows us to externalize configuration so we can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration. Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction, or bound to structured objects via @ConfigurationProperties. Spring Boot uses a very particular @PropertySource order that is designed to allow sensible overriding of values. What happens when our web application has a parent and a child context? The parent context may have some common core functionality and beans, and then one (or multiple) child contexts, maybe containing servlet-specific beans.

In that case, what’s the best way to define properties files and include them in these contexts? And how to best retrieve these properties from Spring?

If the file is defined in the Parent context:

@Value works in Child context: YES @Value works in Parent context: YES environment.getProperty in Child context: YES environment.getProperty in Parent context: YES If the file is defined in the Child context:

@Value works in Child context: YES @Value works in Parent context: NO environment.getProperty in Child context: YES environment.getProperty in Parent context: NO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

MVC Architecture

A

Model: The component that deals with all the data-related logic or business logic is Model

View: This component deals with the UI logic of the application.

Controller: It is an interface between Model and View. It is used to process business logic and incoming requests, manipulate data using the Model component and interact with the Views to give the final output.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define spring annotations

A

In Spring Boot, annotations are used to define various aspects of your application, such as configuring beans, handling requests, enabling security, and more. Here are some commonly used annotations in Spring Boot:

@SpringBootApplication: This annotation is used to indicate the main class of a Spring Boot application. It combines three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.

@RestController: This annotation is used to define a RESTful web service controller. It combines @Controller and @ResponseBody annotations.

@RequestMapping: This annotation is used to map HTTP requests to specific controller methods. It can be applied at the class level or method level to define the base URL or URL patterns for the controller.

@Autowired: This annotation is used for automatic dependency injection. It allows Spring to automatically wire the dependencies by matching the type of the dependency with a bean in the application context.

@Service: This annotation is used to define a service bean. It is typically applied to the service layer classes in your application.

@Repository: This annotation is used to define a repository bean. It is typically applied to the classes that interact with the database or external data sources.

@Configuration: This annotation is used to indicate that a class defines one or more beans. It is often used in conjunction with @Bean to define custom beans in the application context.

@EnableAutoConfiguration: This annotation enables Spring Boot’s auto-configuration feature. It automatically configures the beans and components based on the dependencies and the classpath.

@ComponentScan: This annotation is used to specify the base package(s) for component scanning. It scans the specified package(s) and its sub-packages for Spring components and beans.

@Transactional: This annotation is used to define a transactional method or class. It ensures that the annotated method or all methods of the annotated class run within a transactional context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

@Controller

A

@Controller annotation is a specialization of the @Component annotation.
@Controller replaces the process of expanding any controller base class or referencing the Servlet-specific features.
The class annotated with @Controller has methods mapped using @RequestMapping.
The annotated controller bean may be defined explicitly in the dispatcher’s context.
The classes annotated with @Controller are automatically detected by component scanning.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

To define @RequestMapping annotation

A

A class annotated with@Controller has methods annotated with @RequestMapping. The DipatcherServlet will scan such annotated classes to detect the @RequestMapping.
The @RequestMapping is a class and method level annotation used to map web requests to spring controller methods.
value is used to define the path or URL.
method is used to define either GET or POST or both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

@RequestParam

A

@RequestParam extracts values from the query string.
It is encoded as the values are taken from a query string but not directly from the path.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

@PathVariable

A

@PathVariable extracts values from the URI path.
As it extracts values from the URI path, it is not encoded.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How the Spring @Transactional will work in place of JDBC and hibernate frameworks. And also how can a developer able to control the transactions?

A

The @Transactional annotation in Spring is used to manage transactions declaratively. It simplifies transaction management by handling the low-level details for you. It works with both JDBC and Hibernate frameworks. With @Transactional, you can define transactional boundaries for your methods without dealing with transaction management code explicitly. By annotating methods with @Transactional, Spring creates a proxy and adds transactional behavior to the method calls. You can control transactions by applying @Transactional at the method, class, or interface level. Spring integrates with JDBC or Hibernate transaction management, depending on the underlying technology. To use @Transactional, you need to configure a transaction manager in your Spring application context. Overall, @Transactional provides a convenient and consistent way to manage transactions in your application.

17
Q

How the Spring Data Validation is useful to validate the web application modules when we receive user input.

A

Spring Data Validation is a feature in the Spring Framework that simplifies the validation of user input in web applications. It allows you to declare validation rules using annotations in your domain model classes. Spring Data Validation seamlessly integrates with Spring MVC, providing consistent validation and error handling. It supports built-in validation annotations and allows for custom validation logic. With Spring Data Validation, you can ensure the validity of user input, enhance user experience, and improve the reliability of your web application.

18
Q

Why should you use Spring Boot?

A

There are several compelling reasons to choose Spring Boot for your application development:

Rapid Application Development: Developers can start their projects quickly with Spring Boot, which has pre-configured components, reducing development time and effort by eliminating manual setup.
Spring Boot has pre-configured components that reduce development time and effort
Developers can start their projects quickly with Spring Boot
Manual setup is eliminated
Opinionated Defaults: Spring Boot uses sensible defaults for different aspects of application development, such as dependency management, configuration, and database connectivity. This means less manual configuration is needed in many cases and it encourages the use of best practices.

Spring Boot uses sensible defaults for different aspects of application development
It reduces the need for manual configuration
It encourages the use of best practices
Microservices and Cloud-Native Architecture: Spring Boot works well with Spring Cloud, which makes it a great option for creating microservices and cloud-based apps. It has features such as finding services, tracking them across different machines, and managing configuration in one place.

Spring Boot works well with Spring Cloud for creating microservices and cloud-based apps
Spring Cloud features include finding services, tracking them across different machines, and managing configuration in one place

Integration with the Spring Ecosystem: Spring Boot works well with other Spring components, including Spring Data, Spring Security, and Spring MVC. This lets developers use all of Spring’s powerful features while also taking advantage of Spring Boot’s easy-to-use design.
Spring Boot integrates well with other Spring components, including Spring Data, Spring Security, and Spring MVC.
Developers can use all of Spring’s powerful features while also taking advantage of Spring Boot’s easy-to-use design.
Embedded Server and Deployment Flexibility: Spring Boot comes with a built-in servlet container like Tomcat or Jetty, which lets you run your application as a JAR file by itself. You can deploy it in many ways, such as on traditional servers, in containers like Docker, or using serverless architectures.

Spring Boot includes a built-in servlet container like Tomcat or Jetty.
Applications can be run as a JAR file by itself.
Applications can be deployed in various ways, including on traditional servers, in containers like Docker, or using serverless architectures.

19
Q

Getting started with Spring Boot

A

To start using Spring Boot, you need to have Java Development Kit (JDK) installed on your computer. You can create a Spring Boot project using either Maven or Gradle as build tools. Both tools are great for managing dependencies and building Java projects.

After setting up your development environment, you can create a new project using Spring Initializr or command-line tools. Spring Initializr is a web-based tool that helps you generate a basic project structure with the necessary dependencies.

20
Q

Inversion of Control

A

The IOC container is a tool in Spring Boot that handles objects and their dependencies. Instead of the programmer handling objects themselves, the IOC container does it for them. The programmer only needs to define the objects and their dependencies, and the container takes care of creating and setting them up. This makes the application more modular and flexible.

The IOC container in Spring Boot handles objects and their dependencies
The container generates and prepares objects according to the definitions provided by the programmer.
The programmer only needs to define the objects and their dependencies, making the application more modular and flexible

21
Q

Beans

A

In Spring Boot, a bean is an object that is taken care of by the Spring IoC (Inversion of Control) container. The container creates and sets up the beans, puts in the things they need, and makes sure they’re doing what they’re supposed to be doing. Beans are set up using Java annotations or XML configuration files.

By default, Spring beans are created as single instances (singleton). This means that the Spring IoC container creates only one instance of a bean and shares it among multiple parts of the application that need it. If you need to create multiple instances of a bean, you can use the @Scope annotation to change the bean’s scope to prototype.

A bean is an object in Spring Boot that is managed by the Spring IoC container.
The container takes care of creating and setting up the beans.
Beans are set up using Java annotations or XML configuration files.
The container ensures that beans have what they need and are functioning correctly.
Spring beans are created as single instances by default
The Spring IoC container creates only one instance of a bean and shares it among multiple parts of the application that need it
To create multiple instances of a bean, use the @Scope annotation to change the bean’s scope to prototype

22
Q

Exception Handling in Spring Boot

A

Spring Boot provides robust support for handling exceptions and returning appropriate error responses. You can use the @ExceptionHandler annotation to define methods that handle specific exceptions.

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<Map<String, Object>> handleResourceNotFoundException(ResourceNotFoundException ex) {
	Map<String, Object> map = new HashMap<>();
map.put("timestamp", new Date(System.Curent...));
map.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(map);
} } @RestControllerAdvice annotation used to create a class that handles exceptions in a centralized way for all the controllers @ExceptionHandler(ResourceNotFoundException.class) annotation used to indicate that the following method handles exceptions of type ResourceNotFoundException @ResponseStatus(HttpStatus.NOT_FOUND) annotation used to set the HTTP response status code to 404 (Not Found) handleResourceNotFoundException(ResourceNotFoundException ex) method handles the exception by creating a map containing the timestamp and error message and returning it as a response entity
23
Q

Handling Forms and Request Parameters

A

Spring Boot provides several ways to handle form submissions and request parameters. You can use the @RequestParam annotation to bind request parameters to method parameters.

// Example: http://localhost:8080/yolp/api/auth/users?username=bduong0929&email=bduong0929@gmail.com
@PostMapping(“/users”)
public ResponseEntity<User> createUser(@RequestParam String username, @RequestParam String email) {
// Create a new user with the provided username and email
User user = new User(username, email);</User>

// Save the user to the database
User savedUser = userService.createUser(user);

return ResponseEntity.created(URI.create("/users/" + savedUser.getId())).body(savedUser); } The createUser method does something when someone does a POST request to /users. When you do the request, you have to include username and email. The @RequestParam annotation helps the method to get the right values for those things.