×
Community Blog What is the Difference between Spring Boot and Spring?

What is the Difference between Spring Boot and Spring?

This article compares and contrasts Spring and Spring Boot.

Overview

When I started learning Spring Boot, I was also confused about the differences between Spring Boot and Spring. I have heard many conflicting answers to this problem, but with the accumulation of my experience, I started to understand the differences between the two frameworks better.

I believe some students that have used Spring Boot for a long time still don't understand the difference between Spring Boot and Spring. After reading my comparisons in the article, maybe you will have different answers and opinions!

What Is Spring?

As a Java developer, Spring is familiar to all. In short, the Spring Framework provides comprehensive infrastructure support for developing Java applications. It contains some good functions, such as dependency injection and out-of-the-box modules, including Spring JDBC, Spring MVC, Spring Security, Spring AOP, and Spring ORM, Spring Test.

These modules shorten the development time of applications and improve 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 database. However, we can simplify the operation into a few lines of code using the JDBCTemplate of the Spring JDBC module.

What Is 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.

Spring Boot has the following characteristics:

1) Create an independent Spring application

2) Embedded Tomcat, Jetty, and Undertow containers (war files are not required).

3) Provides simplified construction configuration of starters

4) Configure spring applications as automatically as possible

5) Provide production indicators, such as indicators, robust inspection, and externalized configuration

6) There are no code generation and XML configuration requirements at all.

Analyzing the Two Frameworks from the Configuration

1. 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 requires 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>

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

Another good example is the test Library. We usually use Spring Test, JUnit, Hamcrest, and Mockito libraries. In Spring projects, we should add all these libraries as dependencies. However, in Spring Boot, we only need to add the spring-boot-starter-test dependency to include these libraries automatically.

Spring Boot provides many dependencies for different Spring modules.

Some of the most commonly used dependencies are listed below:

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 starters, please check the Spring documentation.

2. MVC Configuration

Let's take a look at the configurations required for Spring and Spring Boot to create a JSP Web application.

Spring needs to define the scheduler servlet, mapping, and other support configurations. We can do this using the web.xml file or the Initializer class:

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 parser 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;
   }
}

Once we have added a Web launcher, Spring Boot only needs to configure several properties in the application configuration file to complete the operations above:

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

All Spring configurations above are included automatically by adding Boot web starter through a process called auto-configuration.

This means Spring Boot will review the dependencies, properties, and beans that exist in the application and configure the properties and beans according to these dependencies. If you want to add your custom configuration, Spring Boot auto-configuration will be returned.

3. Configure the Template Engine

Now, let's take a look at how to configure the Thymeleaf template engine in Spring and Spring Boot.

In Spring, we need to add thymeleaf-spring5 dependencies and some configuration for the view parser:

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

Spring Boot1X requires only spring-boot-starter-thymeleaf dependencies to enable Thymeleaf support in Web applications.

However, due to the new features in Thymeleaf3.0, we must add thymeleaf-layout-dialect as a dependency in SpringBoot2XWeb applications. After configuring the dependencies, we can add templates to the src/main/resources/templates folder. Spring Boot will display them automatically.

4. Configure Spring Security

For simplicity, we use the framework's default HTTP Basic authentication. First, let's take a look at the dependencies and configurations required to enable Security using Spring.

Spring must depend on the spring-security-web and the spring-security-config modules. Next, we need to add a class that extends the WebSecurityConfigurerAdapter and uses 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. However, we only need to define the dependency of spring-boot-starter-security because this will add all relevant dependencies to the Classpath automatically.

The security configuration in Spring Boot is the same as above.

Application Launch Boot Configuration

The basic difference between application Boot in Spring and Spring Boot is in the servlet.

Spring uses web.xml or springservletercontainerinitializer as its boot entry point.

Spring Boot only uses the Servlet 3 feature to Boot applications. Let's learn more about it.

1. Spring Boot Configuration

Spring supports the traditional web.xml boot method and the latest Servlet 3 + method. To configure the web.xml method startup:

1) Servlet container (server) reads web.xml

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

3) DispatcherServlet creates WebApplicationContext by reading WEB-INF / {servletName} -servlet.xml.

Finally, DispatcherServlet registers the bean defined in the context of the application. Spring startup steps using Servlet 3 + method. Container searches for the classes that implement ServletContainerInitializer and executes springservcontainerinitializer to find the classes that implement WebApplicationInitializer.

WebApplicationInitializer creates a WebApplicationInitializer that has the XML or @context Configuration class that creates the DispatcherServlet with the context created previously.

2. Spring Boot Configuration

The entry point for 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 embedded containers 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 responsible for binding Servlet, Filter, and ServletContextInitializer bean from the application context to the embedded servlet container.

Another feature of Spring Boot is that it scans all classes in the same package or components in sub-packages of the Main class automatically.

Spring Boot provides a way to deploy it to an external container. We only need to extend the 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 searches for the Main-class, which is defined in the MANIFEST.MF file of the META-INF folder under the war package.

SpringBootServletInitializer is responsible for binding the Servlet, Filter, and ServletContextInitializer.

Packaging and Deployment

Finally, let's take a look at how to package and deploy applications. Both frameworks support generic package management technologies, such as Maven and Gradle. However, these frameworks vary in terms of deployment. For example, the Spring Boot Maven plugin provides Spring Boot support in Maven. It also allows an executable jar or war package to be packaged and ran in place.

Spring Boot has the following advantages over Spring Boot in deployment environments:

  • Provides embedded container support
  • Use the java -jar command to run the jar package independently
  • When deploying in an external container, you can exclude dependencies to avoid potential jar conflicts
  • Flexibility in specifying configuration file options at the deployment time
  • Random Port generation for integration testing

Conclusion

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

Article originally published on WeChat Account Programmer Bai Nannan

Disclaimer: The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments

Alibaba Clouder

2,599 posts | 762 followers

Related Products