What is the difference between Spring and Spring Boot?

Posted May 28, 20208 min read

Overview

As for the difference between Spring and SpringBoot, I heard many answers. When I first started learning SpringBoot, I was also confused. With the accumulation of experience, I slowly understood these two frameworks. What is the difference? I believe that for students who have used SpringBoot for a long time, they still do n t understand the difference between SpringBoot and Spring. After reading the comparison in the article, maybe you have different answers and opinions !

What is 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:
SpringJDBC, SpringMVC, SpringSecurity, SpringAOP, SpringORM, SpringTest, these modules shorten the application development time and increase the efficiency of application development. For example, in the early stages of JavaWeb development, we need to write a lot of code to insert records Into the database. But by using the JDBCTemplate of the SpringJDBC module, we can simplify the operation to a few lines of code.

What is Spring Boot

SpringBoot is basically an extension of the Spring framework, which eliminates the XML configuration required to set up Spring applications, paving the way for a faster and more efficient development ecosystem.

Some features in SpringBoot:

1, Create an independent Spring application.
2, Embedded Tomcat, Jetty, Undertow containers(no need to deploy war files).
3, Provided starters to simplify build configuration
4. Configure the spring application automatically whenever possible.
5 ** Provide production indicators, such as indicators, robustness check and external configuration
**6,
No code generation and XML configuration requirements at all

From configuration analysis

Maven dependency

First, let s take a look at the minimum 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 the web application:

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

During the build, all other dependencies will be automatically added to the project.

Another good example is the test library. We usually use SpringTest, JUnit, Hamcrest and Mockito libraries. In the Spring project, we should add all these libraries as dependencies. But in SpringBoot, we only need to add 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

For a complete list of starter, please see the Spring documentation.

MVC configuration

Let's take a look at the configuration required by Spring and SpringBoot to create a JSPWeb application.

Spring needs to define the scheduler servlet, mapping and other supporting configurations. We can use the web.xml file or the Initializer class to do 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 parse 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;
    }
}

Let's look at SpringBoot once we added the Web startup program, SpringBoot only needs to configure a few properties in the application configuration file to complete the above operation:

  1. spring.mvc.view.prefix =/WEB-INF/jsp /
  2. spring.mvc.view.suffix = .jsp

All Spring configuration above is automatically included by adding Bootweb starter through a process called auto-configuration.

This means that SpringBoot will look at the dependencies, properties and bean present in the application and configure the properties and bean based on these dependencies. Of course, if we want to add our own custom configuration, then the automatic configuration of SpringBoot will be returned.

Configure template engine

Now let's see how to configure Thymeleaf template engine in Spring and Spring Boot.

In Spring, we need to add thymeleaf-spring5 dependency and some configuration for 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 requires spring-boot-starter-thymeleaf dependencies 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. After configuring the dependencies, we can add templates to the src/main/resources/templates folder and SpringBoot will automatically display them.

Spring Security configuration

For simplicity, we use the framework's default HTTPBasic authentication. Let's first look at the dependencies and configuration required to enable Security using Spring.

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 annotate it with @ EnableWebSecurity:

@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, SpringBoot also needs these dependencies to make it work. But we only need to define the dependency of spring-boot-starter-security, because this will automatically add all related dependencies to the classpath.

The security configuration in SpringBoot is the same as above.

Application startup boot configuration

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

Spring boot configuration

Spring supports the traditional web.xml boot method and the latest Servlet3 + method.

Steps to configure web.xml method startup

Servlet container(server) reads web.xml

The DispatcherServlet defined in web.xml is instantiated by the container

DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName} -servlet.xml. Finally, DispatcherServlet registers the bean defined in the application context

Spring startup steps using the Servlet3 + method

The container searches for the class that implements ServletContainerInitializer and executes SpringServletContainerInitializer to find all the classes that implement WebApplicationInitializer ` WebApplicationInitializercreated with the XML or context@ Configuration class WebApplicationInitializercreatedDispatcherServlet ` and the previously created context.

SpringBoot Boot Configuration

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

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

By default, SpringBoot uses embedded containers to run applications. In this case, SpringBoot uses the publicstaticvoidmain entry point to start the embedded Web server. In addition, it is also responsible for binding Servlet, Filter and ServletContextInitializerbean from the application context to the embedded servlet container. Another feature of SpringBoot is that it automatically scans all classes in the same package or components in sub-packages of the Main class.

SpringBoot provides a way to deploy it to external containers. We only need to extend SpringBootServletInitializer:

/**
* War deployment
* /
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 defined in the MANIFEST.MF file under the META-INF folder under the war package. SpringBootServletInitializer will be responsible for binding Servlet, Filter and ServletContextInitializer .

Package and deploy

Finally, let's see how to package and deploy the application. Both frameworks support common package management technologies such as Maven and Gradle. But in terms of deployment, these frameworks are very different. For example, the Spring Boot Maven plugin provides SpringBoot support in Maven. It also allows packaging executable jar or war packages and in-place running applications.

Some advantages of SpringBoot over Spring in a deployment environment include:

1, Provide embedded container support
2, Use command \ _java -jar \ _ to run jar independently
3, When deploying in an external container, you can choose to exclude dependencies to avoid potential jar conflicts
4, Flexibly specify configuration file options during deployment
5, Random port generation for integration testing

in conclusion

In short, we can say that SpringBoot is just an extension of Spring itself, making development, testing and deployment easier.