1. Overview:

I heard a lot of answers about the difference between Spring and SpringBoot. When I first started learning SpringBoot, I had no idea what the difference was. As I gained more experience, I began to understand the difference. Most people still do not understand the difference between Spring and SpringBoot. After reading the comparison in the article, you may have a different answer and view!

2. 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 nice features like dependency injection and out-of-the-box modules such as: Spring JDBC, Spring MVC, Spring Security, Spring AOP, Spring ORM, Spring Test, these modules can shorten the development time of applications. Improved application development efficiency For example, in the early stages of Java Web development, we had to write a lot of code to insert records into data sources. But by using the JDBCTemplate of the Spring JDBC module, we can simplify this to just a few lines of code to configure.

3. 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.

Here are some features in Spring Boot:

1: Create a standalone Spring application. 2: Embed Tomcat, Jetty Undertow and do not need to deploy them. 3: Provide “Starters” Poms to simplify Maven configuration 4: Automate Spring application configuration whenever possible. 5: Provide production metrics, robustness and external configuration 6: Absolutely no code generation and XML configuration requirements

4. Let’s get familiar with these two frameworks

4.1 Maven dependency

First, let’s look at the minimum dependencies needed 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 a Web application:

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

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

Another good example is test libraries. We usually use the Spring Test, JUnit, Hamcrest, and Mockito libraries. In our Spring project, we should add all of these libraries as dependencies. But in Spring Boot, we just 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

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

4.2 MVC Configuration

Let’s take a lookSpringandSpring BootcreateJSP WebConfiguration required by the application.

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

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

In contrast, 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

All of the above Spring configuration is added through a procedure called auto-configurationBoot web starterTo automatically include.

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.

4.3. Configure the Template Engine

Now let’s look at 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);         returntemplateEngine; } @Override public void configureViewResolvers(ViewResolverRegistry registry) { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); registry.viewResolver(resolver); }}Copy the code

SpringBoot1X requires only a spring-boot-starter-Thymeleaf dependency to enable Thymeleaf support in a Web application. But because of the new features in Thymeleaf3.0, we had to add thymeleaf-layout-dialect as a dependency in our SpringBoot2XWeb application. Once the dependencies are in place, we can add the template to the SRC/main/resources/templates folder, SpringBoot will automatically display them.

4.4. Spring Security Configuration

For simplicity, we use the framework’s default HTTP Basic authentication. Let’s start by looking at the dependencies and configuration required to enable Security using Spring. Spring first relies on the spring-security-Web and spring-security-config modules. Next, we need to add an extension WebSecurityConfigurerAdapter class, and using the @ EnableWebSecurity comments:

@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() {         returnnew BCryptPasswordEncoder(); }}Copy the code

Here we use inMemoryAuthentication to set up authentication. Spring Boot also needs these dependencies to make it work. But we only need to define the spring-boot-starter-Security dependency, because this automatically adds all related dependencies to the classpath.

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

5. Application boot configuration

The basic difference between Application Boot in Spring and Spring Boot is the servlet. Spring using web. XML or SpringServletContainerInitializer as its guide entry point. Spring Boot uses only Servlet 3 functionality to Boot applications, so let’s take a closer look

5.1 How does Spring boot configuration?

Spring supports the traditional web.xml boot approach as well as the latest Servlet 3+ approach.

Let’s look at the steps of the web.xml method:

The Servlet container (server) reads the DispatcherServlet defined in web.xml and is instantiated by the container by reading web-INF / {servletName} -servlet.xml to create the WebApplicationContext. Finally, DispatcherServlet registers beans defined in the application context

Here is the Spring boot using the Servlet 3+ method:

Container search implementation ServletContainerInitializer class and executes SpringServletContainerInitializer find WebApplicationInitializer implement all kind WebApplicationInitializer create an XML or context @ the Configuration class WebApplicationInitializer create the context of the DispatcherServlet and created earlier.

5.2 How is SpringBoot configured?

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 an embedded container to run applications. In this case, Spring Boot uses the public static void Main entry point to launch the embedded Web server. In addition, it also is responsible for the Servlet 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. In this case, we must extend SpringBootServletInitializer:

/** * War deployment ** @author SanLi * Created by [email protected] on 2018/4/15 */ public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {returnapplication.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.

Package and deploy

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.

Some of the advantages of Spring Boot versus Spring in a deployment environment include:
  • Provides embedded container support
  • Using the command
    java -jar

    Run the JAR independently

  • When deployed in an external container, you can choose to exclude dependencies to avoid potential JAR conflicts
  • Flexibility in specifying configuration file options during deployment
  • Random port generation for integration tests

7, the conclusion

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

Feel good please like support, welcome to leave a message or enter my crowd 855801563 to get [architecture data topic collection of 90 issues], [BATJTMD Big factory JAVA interview real questions 1000+], this group is dedicated to learning exchange technology, share interview opportunities, refuse advertising, I will also in the group irregularly answer questions, discussion.