Home > Java > javaTutorial > What are the interview questions and answers for SpringBoot?

What are the interview questions and answers for SpringBoot?

WBOY
Release: 2023-05-13 14:16:06
forward
1401 people have browsed it

1. What is Spring Boot?

Spring Boot is a sub-project under the Spring open source organization. It is a one-stop solution for Spring components. It mainly simplifies the difficulty of using
Spring, saves heavy configuration, and provides various startups. tool so that developers can get started quickly.

2. Why use SpringBoot

Fast development, rapid integration, simplified configuration, and embedded service container

3. The difference between SpringBoot and SpringCloud

SpringBoot It is a rapidly developed Spring framework. SpringCloud is a complete microservice framework. SpringCloud depends on SpringBoot.

4. What are the advantages of Spring Boot?

Spring Boot mainly has the following advantages: It is easy to get started, improves development efficiency, and provides a faster and simpler development framework for Spring development. Works right out of the box, away from cumbersome configuration. It provides a series of non-business functions common to large-scale projects, such as embedded servers, security management, operating data monitoring, health check and external configuration, etc. The summary of SpringBoot is to make coding simpler, configuration simpler, deployment simpler, monitoring simpler, etc.

5. What is the core annotation of Spring Boot?

What annotations does it mainly consist of? The annotation on the startup class is @SpringBootApplication, which is also the core annotation of Spring Boot. The main combination includes the following three annotations: @SpringBootConfiguration: combines the @Configuration annotation to implement the function of the configuration file. @EnableAutoConfiguration: Turn on the automatic configuration function, or turn off an automatic configuration option. For example:
java If you turn off the data source automatic configuration function: @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }).
@ComponentScan: Spring component scan. 6. What logging frameworks does Spring Boot support? What is the recommended and default logging framework?

Spring Boot supports Java Util Logging, Log4j2, and Lockback as logging frameworks. If you use Starters to launch

, Spring Boot will use Logback as the default logging framework, but it supports no matter what kind of logging framework it is. Output the configuration

file to the console or file.

7. The working principle of SpringBoot Starter

I personally understand that SpringBoot is composed of various Starters. We can also develop the Starter ourselves. The @SpringBootApplication annotation will automatically go to maven when springBoot starts. Read the

spring.factories file in each starter, which configures all the beans that need to be created in the spring container, and performs automatic configuration to inject the

bean into the SpringContext // (SpringContext is Spring's Configuration file)

8. What are the new features of Spring Boot 2.X? How is it different from 1.X?

Configuration change JDK version upgrade Third-party class library upgrade Responsive Spring programming supports HTTP/2 Supports configuration attribute binding More improvements and enhancements

9. What front-end templates does SpringBoot support

thymeleaf, freemarker, jsp, JSP is not officially recommended and will have restrictions

10. Disadvantages of SpringBoot

I think it is embarrassing. At present, I think SpringBoot has no shortcomings. When I found one, I thought it was because I didn’t have to configure it myself, so it was difficult to locate when an error was reported.

11. What are the ways to run Spring Boot?

Package with commands or put it in a container to run

Use Maven/Gradle plug-in to run

Directly execute the main method to run

12. Does Spring Boot need to be run in an independent container?

No need, there are built-in containers such as Tomcat/Jetty.

13. What are the ways to enable Spring Boot features?

Inherit the spring-boot-starter-parent project

Import the spring-boot-dependencies project dependencies


14. What are the ways to implement hot deployment in SpringBoot?

Hot deployment means that the operation background code can be automatically updated to the running project without re-running the SpringBoot project.

There are two main ways:

Spring Loaded
Spring-boot-devtools

15. The use of SpringBoot things

SpringBoot things are very simple. First use the annotation EnableTransactionManagement to open the thing, and then add the annotation Transactional to the

Service method.


16. Async asynchronous calling method

Using asynchronous calling in SpringBoot is very simple. You only need to use the @Async annotation on the method to achieve asynchronous

calling of the method. Note: You need to add @EnableAsync to the startup class to make the asynchronous call @Async annotation take effect.


17. How to run some specific code when Spring Boot starts?

You can implement the interface ApplicationRunner or CommandLineRunner. These two interfaces are implemented in the same way. They

only provide one run method


18. What are the several ways to read configuration in Spring Boot? Way?

Spring Boot can bind variables through @PropertySource, @Value, @Environment, @ConfigurationPropertie annotation

19. What is JavaConfig?

Spring JavaConfig is a product of the Spring community. It was introduced in Spring 3.0. It provides a
pure Java method for configuring the Spring IOC container. So it helps avoid using XML configuration. The advantages of using JavaConfig are:
Object-oriented configuration. Because configurations are defined as classes in JavaConfig, users can take full advantage of object-oriented features in Java. One configuration class can inherit another, override its @Bean methods, etc.
Reduce or eliminate XML configuration. The benefits of externalized configuration based on dependency injection principles have been proven. However, many developers don't want to switch back and forth between XML and Java. JavaConfig provides developers with a pure Java way to configure Spring containers similar to XML configuration concepts. From a technical perspective, it is possible to configure a container using only the JavaConfig configuration class, but in practice many people believe that mixing and matching JavaConfig with XML is ideal.
Type safe and refactoring friendly. JavaConfig provides a type-safe way to configure Spring containers. Thanks to Java
5.0's support for generics, it is now possible to retrieve beans by type instead of by name, without requiring any casts or string-based lookups.
Commonly used Java config:
@Configuration: Write this annotation on the class to indicate that this class is a configuration class
@ComponentScan: Add the @ComponentScan annotation on the configuration class. By default, this annotation will scan all configuration classes under the package where this class is located, which is equivalent to the previous .
@Bean: bean injection: equivalent to the previous < bean id="objectMapper"
class="org.codehaus.jackson.map.ObjectMapper" />
@EnableWebMvc: equivalent to xml
@ImportResource: Equivalent to xml< import resource="applicationContextcache.xml">

20. What is the automatic configuration principle of SpringBoot

Mainly the core annotation on Spring Boot's startup class, the SpringBootApplication annotation main configuration class. With this main configuration

, an @EnableAutoConfiguration annotation automatic configuration function will be enabled for Spring Boot when the class starts.
With this EnableAutoConfiguration, it will:
Load the auto-configuration classes that may be used from the configuration file META_INF/Spring.factories
Remove duplication, and exclude the classes carried by the exclude and excludeName attributes
Filter , return the automatic configuration classes that meet the condition (@Conditional)

21. How do you understand the Spring Boot configuration loading order?

In Spring Boot, you can use the following methods to load configuration.

1.properties file;
2.YAML file;
3.System environment variables;
4.Command line parameters;
etc.……

22 . What is YAML?

YAML is a human-readable data serialization language. It is usually used in configuration files. Compared to properties files, YAML files are more structured and less confusing if we want to

add complex properties in a configuration file. It can be seen that YAML has hierarchical configuration data.

23. What are the advantages of YAML configuration?

YAML can now be regarded as a very popular configuration file format. Whether it is front-end or back-end, you can see YAML configuration

set. So what are the advantages of YAML configuration compared with traditional properties configuration?

Orderly configuration, in some special scenarios, orderly configuration is critical
Concise and clear, it also supports arrays, the elements in the array can be basic data types or objects
Compared with properties configuration File, YAML has another disadvantage, that is, it does not support the @PropertySource annotation to import
customized YAML configuration.

24. Can Spring Boot use XML configuration?

Spring Boot recommends using Java configuration instead of XML configuration, but XML configuration can also be used in Spring Boot through @ImportResource Annotations can introduce an XML configuration.

25. What is the core configuration file of spring boot? What is the difference between bootstrap.properties and application.properties?

It may not be easy to encounter the bootstrap.properties configuration file when simply doing Spring Boot development, but when combined with Spring Cloud, this configuration will be encountered frequently. Especially when you need to load some remote configuration files.

Spring boot core two configuration files:

bootstrap (. yml or . properties): boostrap is loaded by the parent ApplicationContext and is loaded before application. The configuration takes effect in the boot phase of the application context. Generally speaking, we will use this file in Spring Cloud configuration. And the properties in boostrap cannot be overridden;

application (. yml or . properties): loaded by ApplicationContext, used for automated configuration of the spring boot project
.

26. What are Spring Profiles?

During project development, some configuration files may be different in different environments such as development, testing or production, such as database connection
, redis configuration, etc. So how do we automatically switch configurations in different environments? Spring provides us with the
profiles mechanism that provides us with the function of switching configuration files back and forth.
Spring Profiles allows users to register beans based on configuration files (dev, test, prod, etc.). So when the application
is run in development, only certain beans can be loaded, while in PRODUCTION, certain other beans can be loaded.
Assume our requirement is that Swagger documentation is only available in the QA environment and all other documentation is disabled. This can be done using configuration files. Spring Boot makes working with configuration files very easy.

27. SpringBoot multi-data source splitting idea

First configure two data sources in the properties configuration file, create a subpackage mapper, and use @ConfigurationProperties

to read the properties in the properties Configuration, use @MapperScan to register into the corresponding mapper package

28. How to manage SpringBoot multi-data source transactions

The first way is to use transactionManager to specify in @TransactionManager of the service layer

Transactions configured in DataSourceConfig
The second is to use jta-atomikos to implement distributed transaction management

29. What are the methods to protect Spring Boot applications?

Use HTTPS in production

Check your dependencies with Snyk
Upgrade to the latest version
Enable CSRF protection
Use Content Security Policy to prevent XSS attacks

30. How to implement security in Spring Boot applications?

In order to implement Spring Boot security, we use the spring-boot-starter-security dependency and

security configuration must be added. It requires very little code. Configuration classes will have to extend WebSecurityConfigurerAdapter and override its methods.

31. Compare the advantages and disadvantages of Spring Security and Shiro?

Since Spring Boot officially provides a large number of very convenient starters out of the box, including Spring Security's

Starter makes it easier to use Spring Security in Spring Boot. You only need to add a dependency to protect all interfaces. Therefore, if it is a Spring Boot project, Spring Security is generally selected. Of course, this is just a suggested combination. From a purely technical point of view, no matter how you combine it, there will be no problem. Compared with Spring Security

, Shiro mainly has the following characteristics:
Spring Security is a heavyweight security management framework; Shiro is a lightweight security management framework
Spring Security has complex concepts and configuration Cumbersome; Shiro has simple concepts and simple configuration
Spring Security has powerful functions; Shiro has simple functions

32. How to solve cross-domain problems in Spring Boot?

Cross-domain can be done through JSONP on the front end Solved, but JSONP can only send GET requests and cannot send other types of requests. In RESTful-style applications, it is very useless. Therefore, we recommend using (CORS, Crossorigin resource sharing) on ​​the back end to solve cross-origin requests. domain issues. This solution is not unique to Spring Boot. In the traditional

SSM framework, CORS can be used to solve cross-domain problems. However, before we configured CORS in XML files,

now we can implement WebMvcConfigurer The interface then overrides the addCorsMappings method to solve cross-domain issues.

@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);
	}
}
Copy after login

33. What is a monitor in Spring Boot?

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

34. How to use Spring Boot to implement global exception handling?

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

35. How do we monitor all Spring Boot microservices?

Spring Boot provides monitor endpoints to monitor metrics for individual microservices. These endpoints are useful for getting information

about applications (like whether they are started) and whether their components (like databases, etc.) are running properly. However, one major disadvantage or difficulty of using monitor

is that we have to open the application's knowledge point individually to know its status or health. Imagine a microservice involving 50 applications, 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 at . It is built on top of Spring Boot Actuator, which provides a web UI that allows us to visualize the metrics of multiple applications.

36. SpringBoot性能如何优化

如果项目比较大,类比较多,不使用@SpringBootApplication,采用@Compoment指定扫包范

在项目启动时设置JVM初始内存和最大内存相同
将springboot内置服务器由tomcat设置为undertow

37. 如何重新加载 Spring Boot 上的更改,而无需重新启动服务器?Spring Boot项目如何热部署?

这可以使用 DEV 工具来实现。通过这种依赖关系,您可以节省任何更改,嵌入式tomcat 将重新启
动。Spring Boot 有一个开发工具(DevTools)模块,它有助于提高开发人员的生产力。Java 开
发人员面临的一个主要挑战是将文件更改自动部署到服务器并自动重启服务器。开发人员可以重新
加载 Spring Boot 上的更改,而无需重新启动服务器。这将消除每次手动部署更改的需要。Spring
Boot 在发布它的第一个版本时没有这个功能。这是开发人员最需要的功能。DevTools 模块完全满
足开发人员的需求。该模块将在生产环境中被禁用。它还提供 H2 数据库控制台以更好地测试应用
程序。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
</dependency>
Copy after login

38. SpringBoot微服务中如何实现 session 共享 ?

在微服务中,一个完整的项目被拆分成多个不相同的独立的服务,各个服务独立部署在不同的服务
器上,各自的 session 被从物理空间上隔离开了,但是经常,我们需要在不同微服务之间共享
session ,常见的方案就是 Spring Session + Redis 来实现 session 共享。将所有微服务的
session 统一保存在 Redis 上,当各个微服务对 session 有相关的读写操作时,都去操作 Redis 上
的 session 。这样就实现了 session 共享,Spring Session 基于 Spring 中的代理过滤器实现,使
得 session 的同步操作对开发人员而言是透明的,非常简便。

39. 您使用了哪些 starter maven 依赖项?

使用了下面的一些依赖项
spring-boot-starter-web 嵌入tomcat和web开发需要servlet与jsp支持
spring-boot-starter-data-jpa 数据库支持
spring-boot-starter-data-redis redis数据库支持
spring-boot-starter-data-solr solr支持
mybatis-spring-boot-starter 第三方的mybatis集成starter
自定义的starter(如果自己开发过就可以说出来)

40. Spring Boot 中的 starter 到底是什么 ?

首先,这个 Starter 并非什么新的技术点,基本上还是基于 Spring 已有功能来实现的。首先它提
供了一个自动化配置类,一般命名为 XXXAutoConfiguration ,在这个配置类中通过条件注解来
决定一个配置是否生效(条件注解就是 Spring 中原本就有的),然后它还会提供一系列的默认配
置,也允许开发者根据实际情况自定义相关配置,然后通过类型安全的属性(spring.factories)注入
将这些配置属性注入进来,新注入的属性会代替掉默认属性。正因为如此,很多第三方框架,我们
只需要引入依赖就可以直接使用了。当然,开发者也可以自定义 Starter

41. Spring Boot 中如何实现定时任务 ?

在 Spring Boot 中使用定时任务主要有两种不同的方式,一个就是使用 Spring 中的 @Scheduled
注解,另一-个则是使用第三方框架 Quartz。
使用 Spring 中的 @Scheduled 的方式主要通过 @Scheduled 注解来实现。

42. spring-boot-starter-parent 有什么用 ?

我们都知道,新创建一个 Spring Boot 项目,默认都是有 parent 的,这个 parent 就是 springboot-starter-parent ,spring-boot-starter-parent 主要有如下作用:
定义了 Java 编译版本为 1.8 。
使用 UTF-8 格式编码。
继承自 spring-boot-dependencies,这个里边定义了依赖的版本,也正是因为继承了这个依
赖,所以我们在写依赖时才不需要写版本号。
执行打包操作的配置。
自动化的资源过滤。
自动化的插件配置。
针对 application.properties 和 application.yml 的资源过滤,包括通过 profile 定义的不同
环境的配置文件,例如 application-dev.properties 和 application-dev.yml。
总结就是打包用的

43. SpringBoot如何实现打包

进入项目目录在控制台输入mvn clean package,clean是清空已存在的项目包,package进行打
包或者点击左边选项栏中的Mavne,先点击clean在点击package

44. What is the difference between the jar produced by Spring Boot and the ordinary jar?

The jar finally packaged by the Spring Boot project is an executable jar. This kind of jar can be directly passed through java -jar xxx.jar Run the
command. This kind of jar cannot be relied on by other projects as an ordinary jar. Even if it is dependent, the classes in it cannot be used.
Spring Boot’s jar cannot be relied upon by other projects, mainly because its structure is different from that of ordinary jars. For ordinary jar packages, after decompression
is directly the package name, and the package is our code. After decompression, the executable jar packaged by Spring Boot is our code in the \BOOTINF\classes directory, so it cannot be Direct quote. If you must reference it, you can add configuration in the pom.xml file and package the Spring Boot project into two jars, one executable and one referenceable.

The above is the detailed content of What are the interview questions and answers for SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template