Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Spring Boot interview questions in java?

2025-05-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the Spring Boot interview questions in java". The explanation in the article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the Spring Boot interview questions in java"?

What is Spring Boot?

Spring Boot, a sub-project of Spring open source organization, is an one-stop solution for Spring components, which mainly simplifies the difficulty of using Spring, saves onerous configuration, provides a variety of initiators, and developers can get started quickly.

What are the advantages of Spring Boot?

Spring Boot has the following main advantages:

Easy to use, improve development efficiency, and provide a faster and more extensive entry experience for Spring development.

Use right out of the box, away from tedious configuration.

It provides a series of common non-business functions for large-scale projects, such as embedded server, security management, running data monitoring, health check and externalized configuration.

There is no code generation and no XML configuration is required.

Avoid a large number of Maven imports and various version conflicts.

Which is the core comment of Spring Boot? What are the main annotations it consists of?

The above annotation of the startup class is @ SpringBootApplication, which is also the core annotation of SpringBoot. The main combination includes the following three annotations:

The above annotation of the startup class is @ SpringBootApplication, which is also the core annotation of SpringBoot. The main combination includes the following three annotations:

@ SpringBootConfiguration: combines @ Configuration annotations to implement the function of configuration files.

@ EnableAutoConfiguration: enable auto-configuration, or turn off an auto-configuration option, such as turning off data source auto-configuration: @ SpringBootApplication (exclude {DataSourceAutoConfiguration.class})

@ ComponentScan:Spring component scan.

Configuration

What is JavaConfig?

Spring JavaConfig is a product of the Spring community that provides a pure Java way to configure Spring IoC containers. So it helps to avoid using XML configurations. The advantages of using JavaConfig are:

(1) object-oriented configuration. Because the configuration is defined as a class in JavaConfig, users can take full advantage of the object-oriented capabilities in Java. One configuration class can inherit another, override its @ Bean method, and so on.

(2) reduce or eliminate XML configuration. The benefits of externalized configuration based on the principle of dependency injection have been proven. However, many developers do not want to switch back and forth between XML and Java. JavaConfig provides developers with a pure Java way to configure Spring containers with concepts similar to XML configuration. From a technical point of view, it is feasible to use only the JavaConfig configuration class to configure the container, but in fact many people think that mixing and matching JavaConfig and XML is ideal.

(3) Type safety and refactoring friendliness. JavaConfig provides a type-safe way to configure Spring containers. Because of Java 5.0support for generics, bean can now be retrieved by type rather than by name without any cast or string-based lookup.

What is the principle of Spring Boot autoconfiguration?

Annotations @ EnableAutoConfiguration, @ Configuration, @ ConditionalOnClass are the core of automatic configuration.

@ EnableAutoConfiguration imports the autoconfiguration class defined in META-INF/spring.factories for the container.

Filter valid autoconfiguration classes.

Each automatic configuration class performs the automatic configuration function with the corresponding xxxProperties.java read configuration file.

How do you understand the loading sequence of Spring Boot configuration?

In Spring Boot, you can load the configuration in several ways.

1) properties file

2) YAML file

3) system environment variables

4) Command line arguments

Wait a minute...

What is YAML?

YAML is a human-readable data serialization language. It is usually used for configuration files. If we want to add complex properties to the configuration file, the YAML file is more structured and less confusing than the properties file. You can see that YAML has hierarchical configuration data.

What are the advantages of YAML configuration?

YAML is now a very popular configuration file format, and YAML configurations can be seen in both the front end and the back end. So what are the advantages of YAML configuration over traditional properties configuration?

Orderly configuration, in some special scenarios, orderly configuration is critical

Arrays are supported, and the elements in the array can be basic data types or objects

Brevity

Another drawback of YAML compared to properties configuration files is that the @ PropertySource annotation is not supported to import custom YAML configurations.

Can Spring Boot be configured using XML?

Spring Boot recommends using Java configuration instead of XML configuration, but XML configuration can also be used in Spring Boot, and a XML configuration can be introduced through the @ ImportResource annotation.

What is the spring boot core profile? What is the difference between bootstrap.properties and application.properties?

It may not be easy to encounter bootstrap.properties configuration files just for Spring Boot development, but this configuration is often encountered when combined with Spring Cloud, especially when you need to load some remote configuration files.

Two configuration files for the spring boot core:

Bootstrap (. Yml or. Properties): boostrap is loaded by the parent ApplicationContext and takes precedence over applicaton, and the configuration takes effect during the boot phase of the application context. Generally speaking, we use it in Spring Cloud Config or Nacos. And the attributes in boostrap cannot be overridden.

Application (. Yml or. Properties): loaded by ApplicatonContext for automated configuration of spring boot projects.

What is Spring Profiles?

Spring Profiles allows users to register bean based on configuration files (dev,test,prod, etc.). Therefore, when the application is running in development, only some bean can be loaded, while in PRODUCTION, some other bean can be loaded. Suppose our requirement is that Swagger documents apply only to the QA environment, and all other documents are disabled. This can be done using a configuration file. Spring Boot makes it easy to use configuration files.

How do I run a Spring Boot application on a custom port?

To run the Spring Boot application on a custom port, you can specify the port in application.properties. Server.port = 8090

Safety

How to implement the security of Spring Boot applications?

To achieve the security of Spring Boot, we use spring-boot-starter-security dependencies and must add security configuration. It requires very little code. The configuration class will have to extend WebSecurityConfigurerAdapter and override its methods.

Compare the advantages and disadvantages of Spring Security and Shiro?

As Spring Boot officially provides a large number of very convenient out-of-the-box Starter, including Spring Security's Starter, it becomes easier to use Spring Security in Spring Boot, and even only needs to add a dependency to protect all interfaces, so if it is a Spring Boot project, generally choose Spring Security. Of course, this is only a suggested combination, purely from a technical point of view, no matter how the combination, there is no problem. Compared with Spring Security, Shiro has the following main characteristics:

Spring Security is a heavyweight security management framework; Shiro is a lightweight security management framework.

Spring Security is complicated in concept and tedious in configuration, while Shiro is simple in concept and configuration.

Spring Security is powerful; Shiro is simple.

How to solve the cross-domain problem in Spring Boot?

Cross-domain can be solved through JSONP at the front end, but JSONP can only send GET requests, but cannot send other types of requests. In RESTful-style applications, it is very fishy, so we recommend (CORS,Cross-origin resource sharing) to solve cross-domain problems at the back end. This kind of solution is not specific to Spring Boot. In the traditional SSM framework, we can solve the cross-domain problem through CORS, but before we configured CORS in the XML file, now we can solve the cross-domain problem by implementing the WebMvcConfigurer interface and then rewriting the addCorsMappings method.

@ Configuration public class CorsConfig implements WebMvcConfigurer {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ *") .allowedOrigins ("*") .allowCredentials (true) .allowedMethods ("GET", "POST", "PUT", "DELETE", "OPTIONS") .maxAge (3600);}}

The front and rear ends of the project are deployed separately, so cross-domain problems need to be solved.

We use cookie to store user login information, control permissions in spring interceptor, and directly return fixed json results to users when permissions do not match.

When the user logs in, it is used normally; when the user logs out of the login state or when the token expires, the cross-domain phenomenon occurs due to the problem of interceptor and cross-domain order.

We know a http request that goes to filter first and then processes the interceptor when it arrives at servlet. If we put cors in filter, it can be executed before permission interceptor.

@ Configuration public class CorsConfig {@ Bean public CorsFilter corsFilter () {CorsConfiguration corsConfiguration = new CorsConfiguration (); corsConfiguration.addAllowedOrigin ("*"); corsConfiguration.addAllowedHeader ("*"); corsConfiguration.addAllowedMethod ("*"); corsConfiguration.setAllowCredentials (true); UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource (); urlBasedCorsConfigurationSource.registerCorsConfiguration ("/ *", corsConfiguration); return new CorsFilter (urlBasedCorsConfigurationSource) }}

What is a CSRF attack?

CSRF stands for cross-site request forgery. This is an attack that forces the end user to perform unwanted actions on the currently authenticated Web application. CSRF attacks specifically target state change requests rather than data theft because attackers cannot view responses to bogus requests.

Monitor

What is the monitor in Spring Boot?

Spring boot actuator is one of the important functions in the spring startup framework. The Spring boot Monitor helps you access the current status of running applications in a production environment. There are several indicators that must be checked and monitored in the production environment. Even though some external applications may be using these services to trigger alert messages to relevant people. The monitor module exposes a set of REST endpoints that can be accessed directly as HTTP URL to check status.

How do I disable Actuator endpoint security in Spring Boot?

By default, all sensitive HTTP endpoints are secure and only users with the ACTUATOR role can access them. Security is implemented using standard HttpServletRequest.isUserInRole methods. We can use it to disable security. It is recommended that security be disabled only if the enforcement endpoint is accessed behind the firewall.

How do we monitor all Spring Boot microservices?

Spring Boot provides monitor endpoints to monitor the metrics of individual micro-services. These endpoints are useful for getting information about applications (such as whether they are started) and whether their components (such as databases, etc.) are functioning properly. However, one of the main drawbacks or difficulties of using the monitor is that we have to open the knowledge points of the application separately to understand its status or health. Imagine a micro-service involving 50 applications, and the administrator would have to hit the execution terminals of all 50 applications. To help us deal with this situation, we will use the open source project located in. It is built on top of Spring Boot Actuator and provides a Web UI that enables us to visualize metrics for multiple applications.

Integrate third-party projects

What is WebSockets?

WebSocket is a computer communication protocol that provides a full-duplex communication channel over a single TCP connection.

1. WebSocket is bi-directional-you can initiate message delivery using a WebSocket client or server.

2. WebSocket is full-duplex-client and server communication is independent of each other.

3. Single TCP connection-the initial connection uses HTTP, and then upgrade this connection to a socket-based connection. Then this single connection is used for all future communications.

4. Light-WebSocket message data exchange is much lighter than http.

What is Spring Data?

Spring Data is a subproject of Spring. Used to simplify database access, support NoSQL and relational data storage. Its main goal is to make database access convenient and fast. Spring Data has the following characteristics:

The SpringData project supports NoSQL storage:

MongoDB (document database)

Neo4j (graphic database)

Redis (key / value store)

Hbase (column Family Database)

Relational data storage technologies supported by the SpringData project:

JDBC

JPA

Spring Data Jpa is committed to reducing the amount of development of the data access layer (DAO). The only thing the developer needs to do is to declare the interface of the persistence layer, and leave the rest to Spring Data JPA to help you! Spring Data JPA uses the name of the specification method to determine what logic the method needs to implement based on the name that conforms to the specification.

What is Spring Batch?

Spring Boot Batch provides reusable functions that are important when dealing with a large number of records, including logging / tracking, transaction management, job processing statistics, job restart, skipping, and resource management. It also provides more advanced technical services and functions to achieve extremely high batch and high performance batch jobs through optimization and partitioning techniques. Simple and complex batch jobs can use frameworks to process important amounts of information in a highly scalable manner.

What is a FreeMarker template?

FreeMarker is a Java-based template engine that initially focused on dynamic web page generation using MVC software architecture. The main advantage of using Freemarker is the complete separation of the presentation layer from the business layer. Programmers can handle application code, while designers can handle html page design. Finally, using freemarker, you can combine these to give the final output page.

How to integrate Spring Boot and ActiveMQ?

For integrating Spring Boot and ActiveMQ, we use dependencies. It requires very little configuration and no boilerplate code.

What is Apache Kafka?

Apache Kafka is a distributed publish-subscribe messaging system. It is an extensible, fault-tolerant publish-subscribe messaging system that enables us to build distributed applications. This is a top-level Apache project. Kafka is suitable for offline and online message consumption.

What is Swagger? Did you implement it with Spring Boot?

Swagger is widely used in visual API, using Swagger UI to provide an online sandbox for front-end developers. Swagger is a tool, specification and complete framework implementation for generating a visual representation of RESTful Web services. It enables the document to be updated at the same speed as the server. When properly defined by Swagger, consumers can use a minimum of implementation logic to understand and interact with remote services. As a result, Swagger eliminates speculation when invoking the service.

The front and rear ends are separated, how to maintain the interface documents?

Front-end separation development is becoming more and more popular. In most cases, we do front-end separation development through Spring Boot. There must be API documentation for front-end separation, otherwise the front and rear ends will be deeply involved in wrangling. A stupid way is to use word or md to maintain interface documents, but the efficiency is too low, when the interface changes, everyone's documentation has to change. In Spring Boot, the common solution to this problem is Swagger. Using Swagger, we can quickly generate an interface document website. Once the interface changes, the document will be updated automatically. All development engineers can visit this online website to get the latest interface documents, which is very convenient.

Other

How do I reload changes on Spring Boot without restarting the server? How is the Spring Boot project hot to deploy?

This can be done using the DEV tool. With this dependency, you can save any changes and the embedded tomcat will restart. Spring Boot has a development tool (DevTools) module that helps increase developer productivity. One of the main challenges for Java developers is to automatically deploy file changes to the server and restart the server automatically. Developers can reload changes on the Spring Boot without restarting the server. This eliminates the need to deploy changes manually each time. Spring Boot didn't have this feature when it released its first version. This is the feature that developers need most. The DevTools module fully meets the needs of developers. This module will be disabled in the production environment. It also provides the H2 database console to better test the application.

Org.springframework.boot spring-boot-devtools

Which starter maven dependencies do you use?

Some of the following dependencies are used

Spring-boot-starter-activemq

Spring-boot-starter-security

This helps to increase fewer dependencies and reduce version conflicts.

What exactly is starter in Spring Boot?

First of all, this Starter is not a new technical point, but is basically based on the existing functions of Spring. First, it provides an automated configuration class, generally named XXXAutoConfiguration, in which conditional annotations are used to determine whether a configuration is valid (the conditional annotations are already in Spring). Then it also provides a series of default configurations and allows developers to customize the relevant configurations according to the actual situation, and then inject these configuration attributes through type-safe attribute injection. The newly injected property replaces the default property. Because of this, many third-party frameworks can be used directly by introducing dependencies. Of course, developers can also customize Starter

What's the use of spring-boot-starter-parent?

As we all know, when a new Spring Boot project is created, there is parent by default. This parent is spring-boot-starter-parent. Spring-boot-starter-parent has the following main functions:

The Java compiler version is defined as 1.8.

Encode in UTF-8 format.

Inherit from spring-boot-dependencies, which defines the version of the dependency, and it is precisely because we inherit this dependency that we do not need to write the version number when writing the dependency.

The configuration that performs the packaging operation.

Automated resource filtering.

Automated plug-in configuration.

Resource filtering for application.properties and application.yml, including profiles for different environments defined by profile, such as application-dev.properties and application-dev.yml.

What is the difference between a Spring Boot jar and an ordinary jar?

The final jar packaged into an Spring Boot project is an executable jar, which can be run directly through the java-jar xxx.jar command. This jar cannot be relied on by other projects as a normal jar, and the classes in it cannot be used even if it is dependent.

Spring Boot's jar cannot be relied on by other projects, mainly because its structure is different from that of a normal jar. For an ordinary jar package, the name of the package is extracted directly, and our code is in the package. After the executable jar packaged by Spring Boot is decompressed, it is our code in the\ BOOT-INF\ classes directory, so it cannot be directly referenced. If you do not need a reference, you can add the configuration in the pom.xml file to package the Spring Boot project into two jar, one executable and one referenced.

What are the ways to run Spring Boot?

1) package command or run in a container

2) run with the Maven/ Gradle plug-in

3) directly execute the main method to run

Does Spring Boot need to be run in a separate container?

Can not be needed, built-in containers such as Tomcat/ Jetty.

What are the ways to turn on the Spring Boot feature?

1) inherit the spring-boot-starter-parent project

2) Import spring-boot-dependencies project dependencies

How to use Spring Boot to implement exception handling?

Spring provides a very useful way to handle exceptions using ControllerAdvice. We handle all the exceptions thrown by the controller class by implementing a ControlerAdvice class.

How to use Spring Boot for paging and sorting?

Using Spring Boot to implement paging is very simple. Using Spring Data-JPA, you can implement the method of passing pageable to the repository.

How to implement session sharing in microservices?

In micro-services, a complete project is divided into several different independent services, each service is independently deployed on different servers, and their session is separated from the physical space, but often, we need to share session among different micro-services. The common solution is Spring Session + Redis to achieve session sharing. The session of all microservices is stored on the Redis, and when each microservice has related read and write operations to the session, it operates the session on the Redis. In this way, session sharing is implemented, and Spring Session is based on the proxy filter implementation in Spring, which makes the synchronization of session transparent and easy for developers.

How to implement scheduled tasks in Spring Boot?

Scheduled tasks are also a common requirement, and the support for scheduled tasks in Spring Boot mainly comes from the Spring framework.

There are two main ways to use timed tasks in Spring Boot, one is to use the @ Scheduled annotation in Spring, and the other is to use the third-party framework Quartz.

The use of @ Scheduled in Spring is mainly achieved through the @ Scheduled annotation.

With Quartz, you can define Job and Trigger in the same way as Quartz.

Thank you for your reading, the above is the content of "what are the Spring Boot interview questions in java". After the study of this article, I believe you have a deeper understanding of what the Spring Boot interview questions in java have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report