The difference between Spring and Spring Boot

I. Overview

When I first started learning Spring Boot, I was at a loss. As I learned, I gradually learned the difference between the two. I believe that for developers who have used Spring Boot for a long time, most of them still don’t understand these two. What is the difference between this framework? After reading this article, you may have a different answer! !

二 、Spring Boot

Spring Boot is basically an extension of the Spring framework. It eliminates the XML configuration required to set up Spring applications, paving the way for a faster and more efficient development ecosystem.
The following are some of the features in Spring Boot:
1: Create an independent spring application.
2: Embed Tomcat, Jetty Undertow and do not need to deploy them.
3: Provide "starters" poms to simplify Maven configuration
4: Automatically configure spring applications as much as possible.
5: Provide production indicators, robust checks and external configuration
6: Absolutely no code generation and XML configuration requirements

Three, Spring

As a Java developer, everyone is familiar with Spring. In short, the Spring framework provides comprehensive infrastructure support for developing Java applications. It contains some good features, such as dependency injection and out-of-the-box modules, such as: Spring JDBC, Spring MVC, Spring Security, Spring AOP, Spring ORM, Spring Test, these modules should be used before, these modules are shortened The application development time improves the efficiency of application development. For example, in the early stages of Java Web development, we need to write a lot of code to insert records into the data source. But by using the JDBCTemplate of the Spring JDBC module, we can simplify this operation to just a few lines of code.

Fourth, Spring and Spring Boot are more advanced

Maven dependency

First, let's take a look at the minimal dependencies required to create a web application using Spring

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-web</artifactId> 
    <version>5.1.0.RELEASE</version> 
</dependency> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-webmvc</artifactId> 
    <version>5.1.0.RELEASE</version> 
</dependency>

Unlike Spring, Spring Boot only needs one dependency to start and run a web application:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-web</artifactId> 
    <version>2.0.6.RELEASE</version> 
</dependency>

In the Spring project, we should add Spring Test, JUnit, Hamcrest and Mockito as dependencies. But in Spring Boot, we only need to add the spring-boot-starter-test dependency to automatically include these libraries.
Spring Boot provides many dependencies for different Spring modules. Some of the most commonly used are:
spring-boot-starter-data-jpa
spring-boot-starter-security
spring-boot-starter-test
spring-boot-starter-web
spring-boot-starter-thymeleaf

MVC configuration

In creating a Web application, Spring needs to define the dispatcher servlet, mapping and other supporting configuration. We can use the web.xml file or the Initializer class to accomplish this:

public class MyWebAppInitializer implements WebApplicationInitializer {
    
     
   
    @Override 
    public void onStartup(ServletContext container) {
    
     
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); 
        context.setConfigLocation("com.pingfangushi"); 
          container.addListener(new ContextLoaderListener(context)); 
          ServletRegistration.Dynamic dispatcher = container 
          .addServlet("dispatcher", new DispatcherServlet(context)); 
        dispatcher.setLoadOnStartup(1); 
        dispatcher.addMapping("/"); 
    } 
} 

You also need to add the @EnableWebMVC annotation to the @Configuration class and define a view resolver to resolve the view returned from the controller:

@EnableWebMvc 
@Configuration 
public class ClientWebConfig implements WebMvcConfigurer {
    
      
   @Bean 
   public ViewResolver viewResolver() {
    
     
      InternalResourceViewResolver bean 
        = new InternalResourceViewResolver(); 
      bean.setViewClass(JstlView.class); 
      bean.setPrefix("/WEB-INF/view/"); 
      bean.setSuffix(".jsp"); 
      return bean; 
   } 
} 

Compared with Spring, we have added a Web launcher. Spring Boot only needs to configure a few properties in the application configuration file to complete the above operations:

spring.mvc.view.prefix=/WEB-INF/jsp/ 
spring.mvc.view.suffix=.jsp 
Configure template engine

How to configure Thymeleaf template engine in Spring and Spring Boot?
In Spring, we need to add thymeleaf-spring5 dependencies and some configuration to the view resolver:

@Configuration 
@EnableWebMvc 
public class MvcWebConfig implements WebMvcConfigurer {
    
     
  
    @Autowired 
    private ApplicationContext applicationContext; 
  
    @Bean 
    public SpringResourceTemplateResolver templateResolver() {
    
     
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); 
        templateResolver.setApplicationContext(applicationContext); 
        templateResolver.setPrefix("/WEB-INF/views/"); 
        templateResolver.setSuffix(".html"); 
        return templateResolver; 
    } 
  
    @Bean 
    public SpringTemplateEngine templateEngine() {
    
     
        SpringTemplateEngine templateEngine = new SpringTemplateEngine(); 
        templateEngine.setTemplateResolver(templateResolver()); 
        templateEngine.setEnableSpringELCompiler(true); 
        return templateEngine; 
    } 
  
    @Override 
    public void configureViewResolvers(ViewResolverRegistry registry) {
    
     
        ThymeleafViewResolver resolver = new ThymeleafViewResolver(); 
        resolver.setTemplateEngine(templateEngine()); 
        registry.viewResolver(resolver); 
    } 
} 

SpringBoot1X only needs the dependency of spring-boot-starter-thymeleaf to enable Thymeleaf support in web applications. But due to the new features in Thymeleaf3.0, we must add thymeleaf-layout-dialect as a dependency in the SpringBoot2X web application. When the dependencies are in place, we can add templates to the src/main/resources/templates folder and SpringBoot will automatically display them.

Spring Security configuration

Spring first needs to rely on spring-security-web and spring-security-config modules. Next, we need to add a class that extends WebSecurityConfigurerAdapter and use the @EnableWebSecurity annotation:

@Configuration 
@EnableWebSecurity 
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
     
   
    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    
     
        auth.inMemoryAuthentication() 
          .withUser("admin") 
            .password(passwordEncoder() 
            .encode("password")) 
          .authorities("ROLE_ADMIN"); 
    } 
   
    @Override 
    protected void configure(HttpSecurity http) throws Exception {
    
     
        http.authorizeRequests() 
          .anyRequest().authenticated() 
          .and() 
          .httpBasic(); 
    } 
      
    @Bean 
    public PasswordEncoder passwordEncoder() {
    
     
        return new BCryptPasswordEncoder(); 
    } 
} 

Here we use inMemoryAuthentication to set up authentication. Similarly, Spring Boot needs these dependencies to make it work. But we only need to define the dependencies of spring-boot-starter-security, because this will automatically add all related dependencies to the classpath.

Five, application boot configuration

The basic difference between application bootstrapping in Spring and Spring Boot is servlet. Spring uses web.xml or SpringServletContainerInitializer as its boot entry point. Spring Boot only uses Servlet 3 function to guide the application, let us understand in detail below

How does Spring Boot guide the configuration?

The entry point of a Spring Boot application is a class annotated with @SpringBootApplication:

@SpringBootApplication 
public class Application {
    
     
    public static void main(String[] args) {
    
     
        SpringApplication.run(Application.class, args); 
    } 
} 

By default, Spring Boot uses an embedded container to run applications. In this case, Spring Boot uses the public static void main entry point to start the embedded Web server. In addition, it is also responsible for binding Servlet, Filter and ServletContextInitializer beans from the application context to the embedded servlet container. Another feature of Spring Boot is that it automatically scans all classes in the same package or components in sub-packages of the Main class. Spring Boot provides a way to deploy it to an external container. In this case, we must extend SpringBootServletInitializer:

/** 
* War部署 
* 
* @author SanLi 
* Created by [email protected] on 2018/4/15 
*/ 
public class ServletInitializer extends SpringBootServletInitializer {
    
     
 
  @Override 
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    
     
      return application.sources(Application.class); 
  } 
 
  @Override 
  public void onStartup(ServletContext servletContext) throws ServletException {
    
     
      super.onStartup(servletContext); 
      servletContext.addListener(new HttpSessionEventPublisher()); 
  } 
} 

Here, the external servlet container looks for the Main-class SpringBootServletInitializer defined in the MANIFEST.MF file under the META-INF folder of the war package and will be responsible for binding Servlet, Filter and ServletContextInitializer.

How does Spring guide the configuration?

Let's take a look at the steps of the web.xml method:
Servlet container (server) reads
the DispatcherServlet defined in web.xml web.xml and instantiates the DispatcherServlet by the container
to create WebApplicationContext by reading WEB-INF/{servletName} -servlet.xml
Finally, DispatcherServlet registers the beans defined in the application context. The
following is Spring Boot using the Servlet 3+ method: The
container searches for the class that implements ServletContainerInitializer and executes
SpringServletContainerInitializer to find all the classes that implement WebApplicationInitializer
WebApplicationInitializer to create XML or context @Configuration class
WebApplicationInitializer to create DispatcherServlet With the previously created context.

Guess you like

Origin blog.csdn.net/qq_44880095/article/details/105576130