What is Spring?

The Spring framework provides comprehensive infrastructure support for open Java applications, including nice 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

What is Spring Boot

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

Some features in Spring Boot:

  • Build a separate Spring application
  • Embedded Tomcat, Jetty, Undertow containers (war file is not required)
  • Provide starters to simplify the setup
  • Automatically configure spring applications whenever possible
  • Provide production metrics, robustness checks, and external configuration
  • No code generation or XML configuration requirements at all

Spring Boot theory + Practice series of tutorials recommended

https://github.com/javastacks/spring-boot-best-practice

Let’s analyze these two dependencies in terms of configuration

Maven dependency

First, let’s look at the minimum dependencies required to create a Web application using Spring

< the 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 >Copy the code

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 >Copy the code

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

Spring Boot provides many dependencies for different Spring modules

Some common ones are

spring-boot-starter-data-jpa
spring-boot-starter-security
spring-boot-starter-test
spring-boot-starter-web
spring-boot-startert-thymeleaf
Copy the code

2. MVC configuration

Let’s take a look at Spring and Spring Boot’s configuration to create a JSP Web application.

Spring needs to define scheduler servlets, mappings, and other supporting configurations, which we can do 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("/"); }}Copy the code

We 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; }}Copy the code

Once we add the Web launcher, Spring Boot only needs to configure a few properties in the Application configuration file to do this:

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

Most of the above Spring configurations are automatically included by adding the Boot Web starter in a process called auto-configuration

This means that Spring Boot will look at the dependencies, properties, and beans that exist in the application and configure the properties and beans based on those dependencies. Of course, if we want to add our own custom configuration, Spring Boot automatic configuration will fall back

3. Configure the template engine

Now let’s see how to configure the Thymeleaf template engine in Spring and Spring Boot

In Spring, we need to add thymeleaf-Spring 5 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);
    }
}
Copy the code

Spring Boot1X requires only the spring-boot-starter-Thymeleaf dependency to start Thymeleaf support in a Web application

But because of the new features in Thymeleaf3.0, we must add thymeleaf-layout-dialect as a dependency in our SpringBoot2XWeb application, configure the dependency, We can add the template to the SRC/main/resources/templates folder, Spring Boot automatically display them

4. Spring Security configuration

For simplicity, we use the framework’s default HTTP Basic authentication, but let’s first look at the dependencies and configuration required to enable Security using Spring

Spring is the first need to rely on the Spring ws-security – web and Spring ws-security – config module, next, we need to add a class, expand WebSecurityConfigurerAdapter And annotated with @enablewebSecurity:

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

Here we use inMemoryAuthentication to set up authentication, and Spring Boot also needs these dependencies for it to work, but we just need to define the spring-boot-starter-Security dependencies, This automatically adds all related dependencies to the classpath.

The application starts the boot configuration

Spring using Web. XML or springServletCintainerInitializer as its guide entry

Spring Boot uses Servlet3 functionality only to Boot applications. Let me take a look at it in detail

1. Spring boot configuration

Spring supports traditional web.xml bootstringing as well as the latest Servlet3 + approach.

Configure the steps to start the web.ml method
  • The Servlet container (server) reads web.xml
  • The DispatcherServlet defined in web.xml is instantiated by the container
  • The DispatcherServlet reads throughWEB-INF/{servletName)-servlet.xmlTo create aWebApplicationContext.

Finally, the DispatcherServlet registers the beans defined in the application context.

Spring startup steps for the Servlet3+ method

Container search implementation ServletContainerInitiazer class and executes SpringServletContainerInitializer find WebApplicationInitializer implement all kind

WebApplicationInitializer create an XML or context @ Cinfiguration classes WebApplicationInitializer create DispatcherServlet with previous context

SpringBoot boot configuration

The entry point for a SpringBoot application is a class annotated with @SpringBootApplication

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

By default, Spring Boot uses the embedded container to run the application. In this case, Spring Boot uses the public static void Main entry point to launch the embedded Web server. In addition, it is responsible for connecting the Servlet, The Filter and ServletContextInitializer bean from the application context is bound to the embedded servlet container. Another feature of Spring Boot is that it automatically scans all classes in the same package or components in subpackages of the Main class. Spring Boot provides a way to deploy it to an external container. We only need to expand 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()); }}Copy the code

Under the external servlet container to find here in the war file under the meta-inf folder of the MANIFEST. MF file defined in the Main – class, SpringBootServletInitializer servlet will be responsible for binding, The Filter and ServletContextInitializer.

Packaging and deployment

Finally, let’s look at how to package and deploy the application. Both frameworks support common package management technologies such as Maven and Gradle. But when it comes to deployment, these frameworks vary widely. For example, the Spring Boot Maven plug-in provides Spring Boot support in Maven. It also allows you to package an executable JAR or WAR package and run the application in place.

In a deployment environment, Spring Boot is somewhat included compared to Spring

  • Provides embedded container support
  • Run the JAR independently using the command java-jar
  • When deployed in an external container, you can choose to exclude dependencies to avoid potential JAR conflicts
  • Flexibility in specifying configuration options during deployment
  • Random port generation for testing