当前位置:网站首页>Sprinboot interview questions
Sprinboot interview questions
2022-07-26 20:57:00 【Superman moving forward】
Tips :springboot Relevant interview questions
SpringBoot And SpringCloud difference
Spring Boot What are the advantages ?
Spring Boot Which is the core annotation of ? Which annotations does it consist of ?
SpringBoot Starter How it works
Spring Boot 2.X What's new ? And 1.X What's the difference? ?
SpringBoot What front-end templates are supported ,
SpringBoot The shortcomings of
function Spring Boot What are the ways ?
Spring Boot Do you need a separate container to run ?
Turn on Spring Boot How do features work ?
SpringBoot How to implement hot deployment ?
Async Call methods asynchronously
How to be in Spring Boot Run some specific code at startup ?
Spring Boot What are the ways to read configuration ?
SpringBoot What is the auto configuration principle of
How do you understand Spring Boot Configure load order ?
YAML What are the advantages of configuration ?
Spring Boot Whether it can be used XML To configure ?
SpringBoot The idea of splitting multiple data sources
SpringBoot How to manage multi data source transactions
Protect Spring Boot What are the methods of application ?
How to achieve Spring Boot Application security ?
Compare the Spring Security and Shiro Advantages and disadvantages of each ?
Spring Boot How to solve cross domain problems in ?
Spring Boot What is the monitor in ?
How to use Spring Boot Implement global exception handling ?
How do we monitor all Spring Boot Microservices ?
SpringBoot How to optimize performance
SpringBoot How to implement session share ?
What do you use starter maven Dependencies ?
Spring Boot Medium starter What is it ?
Spring Boot How to achieve a scheduled task in ?
spring-boot-starter-parent What's the usage? ?
SpringBoot How to implement packaging
Spring Boot It's a fight jar And ordinary jar What's the difference?
Preface
Tips : Here you can add the general content to be recorded in this article :
Tips : The following is the main body of this article , The following cases can be used for reference
What is? Spring Boot?
- Spring Boot yes Spring Subprojects under the open source organization , yes Spring Component one-stop solution , Mainly simplify the use Spring The difficulty of , Simplified heavy configuration , Various starters are available , So that developers can get started quickly .
Why use SpringBoot
- Rapid development of , Fast integration , Configuration simplification 、 Embedded service container
SpringBoot And SpringCloud difference
- SpringBoot It's rapidly developed Spring frame ,SpringCloud It's a complete microservice framework ,SpringCloud Depend on SpringBoot.
Spring Boot What are the advantages ?
- Spring Boot The main advantages are as follows :
- Easy to use , Improve development efficiency , by Spring Development provides a faster 、 A simpler development framework .
- Open the box , Stay away from cumbersome configuration .
- It provides a series of common non business functions for large projects , for example : Embedded Server 、 security management 、 Operation data monitoring 、 Health check and external configuration etc .
- SpringBoot The conclusion is to make coding easier 、 Simple configuration 、 Deployment becomes simple 、 Monitoring becomes simple and so on
Spring Boot Which is the core annotation of ? Which annotations does it consist of ?
The note above the startup class is @SpringBootApplication, So is it Spring Boot Core notes for , The main combinations include the following 3 A note :
@SpringBootConfiguration: Combined @Configuration annotation , Realize the function of configuration file .
@EnableAutoConfiguration: Turn on auto configuration , You can also turn off an auto configuration option , for example :
java For example, turn off the automatic configuration function of data source : @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }).@ComponentScan:Spring Component scan .
Spring Boot What logging frameworks are supported ? Which is the recommended and default logging framework ?
- Spring Boot Support Java Util Logging, Log4j2, Lockback As a logging framework , If you use Starters starter ,Spring Boot Will use Logback As default logging framework , But no matter what kind of logging framework, it supports exporting configuration files to the console or files .
SpringBoot Starter How it works
I personally understand SpringBoot It's made up of all kinds of Starter Combined , We can develop it ourselves Starterstay sprinBoot Start time by @SpringBootApplication The annotation will go automatically maven Read each starter Medium spring.factories file , This file is configured to be created spring In container bean, And automatically configure bean Inject SpringContext in //(SpringContext yes Spring Configuration file for )
Spring Boot 2.X What's new ? And 1.X What's the difference? ?
- Configuration change
- JDK Version update
- Third party class library upgrade
- Response type Spring Programming support
- HTTP/2 Support
- Configure property binding
- More improvements and enhancements
SpringBoot What front-end templates are supported ,
- thymeleaf,freemarker,jsp, The government does not recommend JSP There will be restrictions
SpringBoot The shortcomings of
- I think it's embarrassing ,SpringBoot At present, I don't think there are any shortcomings , I have to find one. I think it's just
- Because you don't have to make your own configuration , It's hard to locate when you report an error .
function Spring Boot What are the ways ?
Package with command or run in container
use Maven/ Gradle Plug-in run
Direct execution main Method run
Spring Boot Do you need a separate container to run ?
- No need , Built in Tomcat/ Jetty Equal container .
Turn on Spring Boot How do features work ?
Inherit spring-boot-starter-parent project
Import spring-boot-dependencies Project dependence
SpringBoot How to implement hot deployment ?
- Hot deployment means you don't have to run it again SpringBoot The project can realize the operation, and the background code can be automatically updated to the project running
- There are two main ways :
- Spring Loaded
- Spring-boot-devtools
SpringBoot The use of things
- SpringBoot It's very simple , First use annotations EnableTransactionManagement After opening things up , And then in Service Add a comment to the method Transactional Can then .
Async Call methods asynchronously
- stay SpringBoot It's easy to use asynchronous calls in , Just use... On the method @Async Annotation can realize asynchronous call of method . Be careful : You need to add @EnableAsync Make asynchronous calls @Async Annotations to take effect .
How to be in Spring Boot Run some specific code at startup ?
- Interface can be implemented ApplicationRunner perhaps CommandLineRunner, These two interfaces are implemented in the same way , They all offer only one run Method
Spring Boot What are the ways to read configuration ?
- Spring Boot Can pass @PropertySource,@Value,@Environment, @ConfigurationPropertie Annotations to bind variables
What is? JavaConfig?
Spring JavaConfig yes Spring Community products ,Spring 3.0 Introduced him , It provides configuration Spring IOC The purity of the container Java Method . So it helps to avoid using XML To configure . Use JavaConfig The advantage is :
Object oriented configuration . Because the configuration is defined as JavaConfig Class in , So users can make full use of Java Object oriented functions in . One configuration class can inherit another , Rewrite its @Bean Such method .
Reduce or eliminate XML To configure . The benefits of externalized configuration based on dependency injection principles have been proven . however , Many developers don't want to be in XML and Java Switch back and forth between .JavaConfig Provides a pure Java Method to configure and XML The concept of configuration is similar Spring Containers . Technically speaking , Use only JavaConfig Configuring classes to configure containers is possible , But in fact, many people think that they will JavaConfig And XML Mixed matching is ideal .
Type safe and refactoring friendly .JavaConfig Provides a type safe way to configure Spring Containers . because Java 5.0 Support for generics , Now you can retrieve by type, not by name bean, No casts or string based lookups are required .
frequently-used Java config:
- @Configuration: Write this annotation on the class , Indicates that this class is a configuration class
- @ComponentScan: Add... To the configuration class @ComponentScan annotation . By default, this annotation will scan all configuration classes under the package where the class is located , Equivalent to the previous <context:component-scan >.
- @Bean:bean The injection of : It's the same as before < bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
- @EnableWebMvc: amount to xml Of <mvc:annotation-driven >
- @ImportResource: amount to xml Of < import resource="applicationContext-cache.xml">
SpringBoot What is the auto configuration principle of
Mainly Spring Boot The core annotation on the startup class of SpringBootApplication Annotation main configuration class , With this main configuration class, it will be SpringBoot To start a @EnableAutoConfiguration Annotation auto configuration function .
With this EnableAutoConfiguration If you do, you'll :
- From the configuration file META_INF/Spring.factories Load auto configuration classes that may be used
- duplicate removal , And will exclude and excludeName Property to carry the class exclusion
- Filter , Will satisfy the condition (@Conditional) The automatic configuration class returns
How do you understand Spring Boot Configure load order ?
stay Spring Boot Inside , There are several ways to load a configuration .
1.properties file ;
2.YAML file ;
3. System environment variable ;
4. Command line arguments ;
wait ……
What is? YAML?
- YAML Is a human readable data serialization language . It is usually used for configuration files . Compared to property file , If we want to add complex properties to the configuration file ,YAML Files are more structured , And less confusion . It can be seen that YAML With hierarchical configuration data .
YAML What are the advantages of configuration ?
YAML Now it's a very popular configuration file format , Whether it's the front end or the back end , You can see it all YAML To configure . that YAML Configuration and traditional properties What are the advantages of configuration ?
Orderly configuration , In some special situations , It's critical to have an orderly configuration
Simple and clear , He also supports arrays , The elements in an array can be basic data types or objects
comparison properties The configuration file ,YAML There is another drawback , It just doesn't support @PropertySource Annotation import custom YAML To configure .
Spring Boot Whether it can be used XML To configure ?
- Spring Boot Recommended Java Configure not XML To configure , however Spring Boot Can also be used in XML To configure , adopt @ImportResource Annotations can introduce a XML To configure .
spring boot What are the core configuration files ?bootstrap.properties and application.properties What's the difference ?
Do it alone Spring Boot Development , It may not be easy to meet bootstrap.properties The configuration file , But in combination Spring Cloud when , This configuration will often encounter , Especially when you need to load some remote configuration files .
spring boot Two configuration files of the core :
- bootstrap (. yml perhaps . properties):boostrap By father ApplicationContext Loaded , Than applicaton Priority load , Configuration takes effect during the boot phase of the application context . Generally speaking, we are Spring Cloud Configuration will use this file . And boostrap The properties inside cannot be overridden ;
- application (. yml perhaps . properties): from ApplicatonContext load , be used for spring boot Automatic configuration of project .
What is? Spring Profiles?
- In the development of the project , Some configuration files are under development 、 It may be different in different environments such as testing or production , For example, database connections 、redis Configuration, etc . How can we automatically switch configurations in different environments ?Spring It provides us with profiles The mechanism provides us with the function of switching configuration files back and forth
- Spring Profiles Allow users to (dev,test,prod etc. ) To register bean. therefore , When the application is running in development , There are only some bean Can be loaded , And in the PRODUCTION in , Some others bean Can be loaded . Suppose our request is Swagger The document only applies to QA Environmental Science , And disable all other documents . This can be done using a configuration file .Spring Boot Make using configuration files very simple .
SpringBoot The idea of splitting multiple data sources
- First in properties Two data sources are configured in the configuration file , Create subcontract mapper, Use @ConfigurationProperties Read properties Configuration in , Use @MapperScan Register to the corresponding mapper In bag
SpringBoot How to manage multi data source transactions
The first way is in service Layer of @TransactionManager Use in transactionManager Appoint DataSourceConfig Transactions configured in
The second is to use jta-atomikos Realize distributed transaction management
Protect Spring Boot What are the methods of application ?
- Used in production HTTPS
- Use Snyk Check your dependencies
- Upgrade to the latest version
- Enable CSRF Protect
- Use content security policies to prevent XSS attack
How to achieve Spring Boot Application security ?
- In order to achieve Spring Boot The security of , We use spring-boot-starter-security Dependencies , And you have to add security configuration . It requires very little code . The configuration class will have to extend WebSecurityConfigurerAdapter And cover the method .
Compare the Spring Security and Shiro Advantages and disadvantages of each ?
because Spring Boot The official offers a lot of very convenient out of the box Starter , Include Spring Security Of Starter , Make in Spring Boot Use in Spring Security It's easier , Even just add a dependency to protect all interfaces , therefore , If it is Spring Boot project , General choice Spring Security . Of course, it's just a combination of suggestions , Technically speaking , Whatever combination , It's all right .Shiro and Spring Security comparison , It mainly has the following characteristics :
Spring Security It is a heavyweight security management framework ;Shiro It's a lightweight security management framework
Spring Security The concept is complex , Complicated configuration ;Shiro Simple concept 、 Simple configuration
Spring Security Powerful ;Shiro Simple function
Spring Boot How to solve cross domain problems in ?
- Cross domain can pass through at the front end JSONP To solve , however JSONP You can only send GET request , Cannot send other types of requests , stay RESTful In the application of style , It's very chicken ribs , So we recommend to go through... In the back end (CORS,Cross-origin resource sharing) To solve cross domain problems . This solution is not Spring Boot Peculiar , In traditional SSM In the frame , You can go through CORS To solve cross domain problems , Just before we were XML Configuration in file CORS , Now it can be done by implementing WebMvcConfigurer The interface is then rewritten addCorsMappings Methods to solve cross domain problems .
@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 code Spring Boot What is the monitor in ?
- Spring boot actuator yes spring One of the important functions in the startup framework .Spring boot Monitors help you access the current state of running applications in your 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 interested people . The monitor module discloses a set of functions that can be directly used as HTTP URL Access to the REST Endpoint to check status .
How to use Spring Boot Implement global exception handling ?
- Spring Provides a way to use ControllerAdvice A very useful way to handle exceptions . We can achieve a ControlerAdvice class , To handle all exceptions thrown by the controller class .
How do we monitor all Spring Boot Microservices ?
- Spring Boot Provide monitor endpoints to monitor the measurement of individual microservices . These endpoints are for getting information about the application ( If they have been activated ) And their components ( Such as database, etc ) It's very helpful if it's working properly . however , One of the main disadvantages or difficulties of using a monitor is , We have to open the knowledge points of the application separately to understand its status or health . Imagine involving 50 Microservices for applications , The administrator will have to hit all 50 Application execution terminal . To help us deal with this situation , We will use the open source project located at . It is based on Spring Boot Actuator above , It provides a Web UI, Enables us to visualize metrics for multiple applications .
SpringBoot How to optimize performance
If the project is large , There are many classes , Don't use @SpringBootApplication, use @Compoment Specify the scan range
Set... At project startup JVM The initial memory is the same as the maximum memory
take springboot The built-in server is made up of tomcat Set to undertow
How to reload Spring Boot Changes on , Without restarting the server ?Spring Boot How to hot deploy the project ?
- This can be used DEV Tools to implement . Through this dependency , You can save any changes , The embedded tomcat will restart .Spring Boot There is a development tool (DevTools) modular , It helps improve developer productivity .Java A major challenge for developers is to automatically deploy file changes to the server and restart the server automatically . Developers can reload Spring Boot Changes on , Without restarting the server . This eliminates the need for every manual deployment change .Spring Boot This feature was not available at the time of its first release . This is what developers need most .DevTools Modules fully meet the needs of developers . The module will be disabled in the production environment . It also provides H2 Database console for better application testing .
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
Copy code SpringBoot How to implement session share ?
- In microservices , A complete project is divided into several different independent services , Each service is independently deployed on a different server , Respective session Separated from physical space , But often , We need to share... Between different microservices session , The common solution is Spring Session + Redis To achieve session share . All microservices session The unity is preserved in Redis On , When each microservice pair session When there are related reading and writing operations , All operate Redis Upper session . That's it session share ,Spring Session be based on Spring Proxy filter implementation in , bring session Is transparent to developers , It's very simple .
What do you use starter maven Dependencies ?
- Some of the following dependencies are used
- spring-boot-starter-web The embedded tomcat and web Development needs servlet And jsp Support
- spring-boot-starter-data-jpa Database support
- spring-boot-starter-data-redis redis Database support
- spring-boot-starter-data-solr solr Support
- mybatis-spring-boot-starter A third party mybatis Integrate starter
- Self defined starter( If you have developed it yourself, you can say it )
Spring Boot Medium starter What is it ?
- First , This Starter It's not a new technology , Basically, it's based on Spring It has functions to realize . First, it provides an automatic configuration class , It is generally named
XXXAutoConfiguration, In this configuration class, condition annotation is used to determine whether a configuration is effective ( The condition annotation is Spring There are some in the Central Plains ), Then it will provide a series of default configurations , It also allows developers to customize the configuration according to the actual situation , And then through type safe properties (spring.factories) Injection injects these configuration properties , The newly injected property will replace the default property . Because of that , A lot of third-party frameworks , We just need to introduce dependency to use it directly . Of course , Developers can also customize Starter
Spring Boot How to achieve a scheduled task in ?
stay Spring Boot There are two main ways to use timed tasks in , One is to use Spring Medium @Scheduled annotation , The other - One is to use a third-party framework Quartz.
Use Spring Medium @Scheduled The way is mainly through @Scheduled Annotation to implement .
spring-boot-starter-parent What's the usage? ?
We all know , Create a new Spring Boot project , By default, there are parent Of , This parent Namely spring-boot-starter-parent ,spring-boot-starter-parent It has the following functions :
- Defined Java The compiled version is 1.8 .
- Use UTF-8 Format encoding .
- Inherited from spring-boot-dependencies, This defines the dependent version , It is precisely because of the inheritance of this dependence , So we don't need to write version number when writing dependency .
- Configuration to perform packaging operations .
- Automated resource filtering .
- Automatic plug-in configuration .
- in the light of application.properties and application.yml Resource filtering , Including passage profile Profiles for different environments defined , for example application-dev.properties and application-dev.yml.
Summary is for packaging
SpringBoot How to implement packaging
- Enter the project directory and enter... On the console mvn clean package,clean Is to empty the existing project package ,package package
- Or click... In the options bar on the left Mavne, First click clean Click on package
Spring Boot It's a fight jar And ordinary jar What's the difference? ?
Spring Boot The project is finally packaged into jar It's executable jar , such jar You can go directly through
java -jar xxx.jarCommand to run , such jar It can't be used as an ordinary jar Dependent on other projects , You can't use the classes even if you depend on them .Spring Boot Of jar Can't be relied on by other projects , Mainly he and the ordinary jar The structure of is different . ordinary jar package , After decompression, it is the package name directly , There's our code in the bag , and Spring Boot Packaged as executable jar After decompressing , stay
\BOOT-INF\classesDirectory is our code , So it can't be quoted directly . If you have to quote , Can be in pom.xml Add configuration... To the file , take Spring Boot The project is packaged into two jar , An executable , One can quote .
边栏推荐
猜你喜欢

Quick start to connection pooling

AI technology, simplifying the complex world | teatalk online application practical series, issue 2

Interceptors

Buu brush inscription 2

Kotlin - coroutinecontext

如何组装一个注册中心?

CentOS7关于Oracle RAC 11GR2部署磁盘分区问题

Marketing and sales document management and workflow solutions

传奇GEE引擎版本如何封挂?通过脚本+引擎封玩家账号教程

【微信小程序】零基础学 | 小程序语法
随机推荐
如何查看你使用的pytorch是否为GPU版本
884. Uncommon words in two sentences - hash table
GOM登录器配置免费版生成图文教程
Group convolution
【微信小程序】零基础学 | 小程序语法
JDBC的引入
Sword finger offer46 translates numbers into strings
LCP 11. 期望个数统计
AI technology, simplifying the complex world | teatalk online application practical series, issue 2
leetcode 数组类
Leetcode's question brushing -- List summary
消息队列——引入的问题:重复消费&顺序消费&分布式事务
QT signal and slot connection (loose coupling)
全球最聪明50家公司公布:中国厂商占据近半,华为名列第一
Installation and configuration of [basic services] [database] Clickhouse
Correlation analysis between [machine learning] variables
LeetCode链表问题——19.删除链表的倒数第N个节点(一题一文学会链表)
New features of ES6
APP自动化测试框架搭建(八)--ATX Server2多设备集群环境搭建
QT driving school subject examination system -- from implementation to release