preface

As Spring Boot is used more and more widely, Spring Boot has become a knowledge point in the interview of Java programmers, many students do not understand Spring Boot so deep, often will be several serial run to dry down!

Take the following Spring Boot q&A:

Q: What do you think is the biggest advantage of Spring Boot?

A: The biggest advantage of Spring Boot is convention over configuration. “Convention over Configuration” is a software design paradigm that allows developers to program according to convention, reducing the number of decisions a software developer has to make and gaining the benefits of simplicity without losing flexibility.

Q: Where is the “convention over configuration” product in Spring Boot?

A: Spring Boot Starter and Spring Boot Jpa are both examples of “convention over configuration”. The Spring Boot Starter initializes resources according to the convention information during startup. Spring Boot Jpa automatically generates Sql by convention, avoiding a lot of invalid code writing. Why is Spring Boot so popular?

Q: How does the Spring Boot Starter work?

A: Spring Boot does a few things when it starts up:

  • (1) Spring Boot looks for the resources/ meta-INF /spring.factories file in the Starter package that the project relies on during startup.

  • The AutoConfigure class is loaded according to the Spring. factories configuration

  • ③ Automatically configure and inject the Bean into the Spring Context according to the conditions of the @Conditional annotation

To sum up, Spring Boot reads the configuration information of the Spring Boot Starter according to the convention, initializes resources based on the configuration information, and infuses the resources into the Spring container. In this way, after Spring Boot is started, all resources are ready, and the corresponding Bean resources can be directly injected during use.

This is just a simple three-part question and I don’t know how many students can answer it completely.

In fact, there are a lot of technical points can be mined in Spring Boot. Today, I sorted out ten high-frequency Spring Boot interview questions for you, hoping to help you in the later interview.

1. How is automatic configuration of Spring Boot implemented?

The SpringBoot project starts with the @SpringBootApplication annotation, which consists of three annotations:

  • @Configuration

  • @ComponentScan

  • @EnableAutoConfiguration

One @ EnableAutoConfiguration is to realize the automatic configuration of entrance, the annotations by @ Import annotations Import AutoConfigurationImportSelector, Load the meta-INF/Spring.Factories configuration information in this class. Then screen out the data with EnableAutoConfiguration as key, load into IOC container, realize automatic configuration function!

2. What is embedded server? Why do we use embedded servers?

Think about what it takes to deploy an application on your virtual machine.

Step 1: Install Java

Part 2: Server to install Web or application (Tomat/Wbesphere/Weblogic, etc.)

Step 3: Deploy the application WAR package

If we want to simplify these steps, how do we do it?

Let’s think about how to make the server part of the application.

All you need is a Virtual machine with Java installed and you can deploy applications directly on it,

Isn’t that cool?

This idea was the genesis of the embedded server.

When we create a deployable application, we will embed the server (for example, Tomcat) in the deployable server.

For example, for a Spring Boot application, you can generate an application JAR that contains Embedded Tomcat. You can then run the Web application as if it were a normal Java application.

An embedded server is the binary file (for example, tomcat.jar) that our executable contains the server.

3, microservices call multiple interfaces at the same time, how to support transactions ah?

Support for distributed transactions can be addressed using Spring Boot integration with Aatomikos, but I generally do not recommend this because using distributed transactions increases the response time of requests and affects the TPS of the system. In practice, the compensation mechanism of messages is used to deal with distributed transactions.

4. What is the relationship between Shiro, Oauth and CAS? Ask next your company authority is how to design, still have be the distinction of these a few concepts.

Cas and OAuth are components that solve single sign-on, shiro is mainly responsible for the security aspects of permissions, so the function points are inconsistent. However, single sign-on and permission control are often used together, so there are cas+ Shiro or Oauth + Shiro combinations.

Token is generally a token generated by the server after the client logs in. The server verifies the token each time the client accesses the token. The token can be saved to the memory or stored in other media. Redis can share sessions. This scenario is common if several front-end Web servers are loaded but users need to log in.

Our company uses oAuth + Shiro to manage background permissions. Oauth is responsible for multi-background unified login authentication, and Shiro is responsible for granting different access permissions to login users.

5. How to choose Restful and Rpc for communication between services?

In traditional SOA governance, RPC is mostly used; Spring Cloud uses restful communication between services by default. RPC communications can be a little more efficient than restful, but for most companies this efficiency makes little difference. I recommend using restful to make it easier to communicate between services implemented in different languages.

6. How to design stateless service?

For stateless services, let’s start with what state is: if a piece of data needs to be shared by multiple services in order to complete a transaction, that data is called state. Services that in turn rely on this “stateful” data are called stateful services, and vice versa.

The stateless service principle does not mean that stateless services are not allowed in microservices architecture. What it really means is that stateful business services should be changed into stateless computing services, and stateful data should be migrated to the corresponding “stateful data services”.

Scenario Description: For example, the data cache and Session cache established in local memory should be transferred to distributed cache for storage in the current microservice architecture, so that the business service becomes a stateless computing node. After migration, on-demand dynamic scaling can be achieved, and micro service applications can dynamically add and delete nodes at runtime, so there is no need to consider how to synchronize cached data.

What are the three common Spring Cache annotations?

Cacheable: declares a method to be Cacheable, storing the result in a cache so that subsequent calls with the same parameters can be taken from the cache without the actual method being executed.

@cachePUT: A method annotated with @cacheput does not check for previously executed results in the cache before execution. Instead, the method is executed each time and the result is stored in the specified cache as a key-value pair.

CacheEvict is used to mark methods or classes that need to clear cached elements. When marked on a class, it means that all methods in the class trigger the cache to be cleared.

8. How to set Spring Boot to support cross-domain requests?

To ensure security, modern browsers must comply with the same origin policy when making HTTP requests. Otherwise, cross-domain HTTP requests are prohibited by default. Different IP addresses (domain names), ports, and protocols (such as HTTP and HTTPS) may cause cross-domain problems.

Common front-end solutions include:

  • ① Use JSONP to support cross-domain request, JSONP implementation of cross-domain request principle is simple to say, is to dynamically create

  • ② Use the mechanism of reaction proxy to solve the cross-domain problem. When the front-end request, the request is first sent to the back-end of the same address, through the back-end request forwarding to avoid cross-domain access.

Later HTML5 supported the CORS protocol. CORS, or Cross-Origin Resource Sharing, is a W3C standard that allows browsers to issue XMLHttpRequest requests to cross-source servers, overcoming the limitation that AJAX can only be used in the same source. It tells the client about the cross-domain limits by adding a special Header[access-Control-Allow-Origin] to the server, and allows XMLHttpRequest to make a cross-domain request if the browser supports CORS and determines that Origin has passed.

If the front end uses the CORS protocol, the back end needs to be configured to support non-same-origin requests. Spring Boot can be configured to support non-same-origin requests in two ways.

First, configure CorsFilter.


@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
          config.addAllowedOrigin("*");
          config.setAllowCredentials(true);
          config.addAllowedMethod("*");
          config.addAllowedHeader("*");
          config.addExposedHeader("*");

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/ * *", config);

        returnnew CorsFilter(configSource); }}Copy the code

You need to configure the code above. The second way is a little easier.

Second, add to the startup class:


public class Application extends WebMvcConfigurerAdapter {  

    @Override  
    public void addCorsMappings(CorsRegistry registry) {  

        registry.addMapping("/ * *")  
                .allowCredentials(true)  
                .allowedHeaders("*")  
                .allowedOrigins("*")  
                .allowedMethods("*"); }}Copy the code

9. What are the differences between JPA and Hibernate? Can JPA support dynamic SQL?

JPA itself is a specification, its essence is an ORM specification (not ORM framework, because JPA does not provide ORM implementation, only specification) because JPA is a specification, so it only provides some related interfaces, but interfaces can not be directly used, JPA requires some KIND of JPA implementation. Hibernate is a set of implementations of JPA.

JPA creates the corresponding table and field according to the annotation of the Entity class. If the table or field needs to be dynamically created, the corresponding Entity class needs to be dynamically constructed and then the whole Entity needs to be refreshed by calling JPA again. Dynamic SQL, myBatis supports the best, jPA can also support, but not as flexible as MyBatis.

10, Spring, Spring Boot and Spring Cloud?

Spring Ioc and Spring Aop are the two core functions of Spring. With the continuous development of these two core functions, Spring has a series of great products such as Spring transaction and Spring Mvc. The result was the Spring Empire, and by the end Spring could solve almost every problem in enterprise development.

Spring Boot is developed on the basis of the strong Spring empire ecosystem. Spring Boot was invented not to replace Spring, but to make it easier for people to use Spring.

Spring Cloud is an ordered collection of frameworks. It takes advantage of the development convenience of Spring Boot to subtly simplify the development of distributed system infrastructure, such as service discovery registry, configuration center, message bus, load balancing, circuit breakers, data monitoring, etc., which can be started and deployed with one click using Spring Boot’s development style.

Spring Cloud is a development framework that provides a series of functions to solve the service governance in microservices architecture, and Spring Cloud is completely developed based on Spring Boot. Spring Cloud integrates excellent components in the open source industry by using the Spring Boot feature, and provides a set of service governance solutions in the micro-service architecture.

Express the relationship between them with a set of inclusion relationships that don’t quite make sense.

Spring ioc/aop > Spring > Spring Boot > Spring Cloud


Like my article, please follow my official account