What is the difference between spring and spring boot?

Time:2021-10-21

summary

aboutSpringandSpringBootWhat’s the difference? I heard a lot of answers and just started to studySpringBootAt that time, I was also confused. With the accumulation of experience, I slowly understood the difference between the two frameworks. I believe it is useful to use themSpringBootFor a long time, I don’t quite understand itSpringBootIn the end andSpringWhat’s the difference? After reading the comparison in the article, maybe you have different answers and opinions!

What is spring

AsJavaDevelopers, everyoneSpringNo stranger, in short,SpringFramework for developmentJavaApplications provide comprehensive infrastructure support. It contains some good functions, such as dependency injection and out of the box modules, such as:  
SpringJDBC、SpringMVC、SpringSecurity、SpringAOP、SpringORM、SpringTest, these modules shorten the development time of application and improve the efficiency of application development. For example, inJavaWebIn the early stages of development, we need to write a lot of code to insert records into the database. But by usingSpringJDBCModularJDBCTemplate, we can simplify the operation into a few lines of code.

What is spring boot

SpringBootBasicallySpringAn extension of the framework, which eliminates the settingSpringRequired by the applicationXML configuration, paving the way for faster and more efficient development of ecosystems.

SpringBootSome features in:

1、Create independentSpringApplication.
2、EmbeddedTomcatJettyUndertowContainer (no need to deploy war files).
3、ProvidedstartersSimplify build configuration
4、Configure as automatically as possiblespringApplication.
5、Provide production metrics, such as metrics, robustness checks, and externalized configurations
6、No code generation andXMLConfiguration requirements

From configuration analysis

Maven dependency

First, let’s 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 requires only one dependency to start and run web applications:

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

All other dependencies are automatically added to the project during the build.

Another good example is the test library. We usually useSpringTestJUnitHamcrestandMockitoLibrary. staySpringIn the project, we should add all these libraries as dependencies. But inIn springboot, we just need to addspring-boot-starter-testDependencies 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

ofstarterFor a complete list of, see the spring documentation.

MVC configuration

Let’s take a lookSpringandSpringBootestablishJSPWebConfiguration required by the application.

SpringScheduler needs to be definedservlet, mapping, and other support configurations. We can useweb.xmlFile orInitializerClass 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@EnableWebMvcAdd comments to@ConfigurationClass 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;
    }
}

Look againSpringBootOnce we addWebStart the program,SpringBootJust inapplicationSeveral properties are configured in the configuration file to complete the above operations:

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

All spring configurations above are added through a process called auto configurationBootweb starterTo automatically include.

That meansSpringBootThe dependencies, properties, and existing in the application will be viewedbeanAccording to these dependencies, the properties andbeanConfigure. Of course, if we want to add our own custom configuration, thenSpringBootAutomatic configuration will be returned.

Configure template engine

Now let’s look at how to configure the thymeleaf template engine in spring and spring boot.

staySpringIn, we need to addthymeleaf-spring5Dependencies and some configurations:

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

SpringBoot1XIt only needsspring-boot-starter-thymeleafTo enableWebIn the applicationThymeleafsupport.   but becauseThymeleaf3.0For the new features in, we mustthymeleaf-layout-dialectAdd asSpringBoot2XDependencies in web applications. After configuring the dependency, we can add the template to thesrc/main/resources/templatesFolder,SpringBootThey are automatically displayed.

Spring security configuration

For simplicity, we use the framework defaultHTTPBasicAuthentication. Let’s first look at usingSpringEnableSecurityRequired dependencies and configurations.

SpringFirst, we need to rely onspring-security-webandspring-security-configmodular. Next, we need to add an extensionWebSecurityConfigurerAdapterAnd use@EnableWebSecurityNotes:

@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 useinMemoryAuthenticationTo set up authentication. Again,SpringBootThese dependencies are also required for it to work. But we just need to definespring-boot-starter-securityBecause this automatically adds all related dependencies to the classpath.

SpringBootThe security configuration in is the same as above

Application boot configuration

SpringandSpringBootThe basic difference between application boot inservletSpringuseweb.xmlorSpringServletContainerInitializerAs its guide entry point.SpringBootUse onlyServlet3Function to guide the application. Let’s learn more about it

Spring boot configuration

SpringSupport traditionalweb.xmlGuidance mode and the latestServlet3+method.

to configureweb.xmlMethod startup steps

ServletContainer (server) readweb.xml

web.xmlDefined inDispatcherServletInstantiated by container

DispatcherServletBy readingWEB-INF/{servletName}-servlet.xmlTo createWebApplicationContext。 last,DispatcherServletRegister the defined in the application contextbean

useServlet3+MethodicalSpringStart step

Container search implementationServletContainerInitializerClass and executeSpringServletContainerInitializerFind and implement all classesWebApplicationInitializer`WebApplicationInitializerCreate a document with XML or context@ConfigurationclassWebApplicationInitializerestablishDispatcherservlet ` is different from the previously created context.

Springboot boot 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,SpringBootUse embedded containers to run applications. under these circumstances,SpringBootusepublicstaticvoidmainEntry point to start embeddedWebThe server. In addition, it is responsible forServletFilterandServletContextInitializerbeanBinding from application context to embeddedservletContainer.SpringBootAnother feature of is that it automatically scans all classes or in the same packageMainClass.

SpringBootProvides a way to deploy it to an external container. We just need to expandSpringBootServletInitializerYou can:

/**
 *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());
    }
}

Outside hereservletThe container looks for the under the war packageMETA-INFDefined in manifest.mf file under folderMain-classSpringBootServletInitializerWill be responsible for bindingServletFilterandServletContextInitializer

Packaging and deployment

Finally, let’s look at how to package and deploy applications. Both frameworks supportMavenandGradleAnd other general package management technologies. However, in terms of deployment, these frameworks are very different. For example, the spring boot Maven plug-inMavenProvided inSpringBootsupport. It also allows you to package executablesjarorwarBao BingLocalRun the application.

In a deployment environmentSpringBootcontrastSpringSome of the benefits of include:

1、Provide embedded container support
2、Use command_ java -jar_ Run jar independently
3、When deploying in an external container, you can choose to exclude dependencies to avoid potential jar conflicts
4、Flexible options for specifying configuration files during deployment
5、Random port generation for integration testing

conclusion

In short, we can saySpringBootjustSpringIts expansion makes development, testing and deployment more convenient.