summary
I have heard many answers about the difference between Spring and SpringBoot. I was confused when I first started to learn SpringBoot. With the accumulation of experience, I gradually understood the difference between the two frameworks.
I believe that for students who have used SpringBoot for a long time, they still don't quite understand the difference between SpringBoot and Spring. After reading the comparison in the article, you may have different answers and views!
What is Spring?
As Java developers, everyone is familiar with Spring. 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, such as:
Spring JDBC ,Spring MVC ,Spring Security, Spring AOP ,Spring ORM ,Spring Test
These modules shorten the development time of applications and improve the efficiency of application development. For example, in the early stage of Java Web development, we need to write a lot of code to insert records into the database. But by using the JDBCTemplate of the Spring JDBC module, we can simplify the operation into a few lines of code.
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.
Some features of Spring Boot:
1) Create a standalone Spring application.
2) Embedded Tomcat, Jetty, Undertow containers (no need to deploy war files).
3) starters are provided to simplify build configuration.
4) Configure spring applications as automatically as possible.
5) Provide production metrics such as metrics, robustness checks, and externalized configurations
6) No code generation and XML configuration requirements at all.
Follow the official account: programmer Bai Nannan obtained a 1184 page PDF of spring family bucket information.
Let's analyze these two frameworks from the perspective of configuration
1. 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 use the Spring Test, JUnit, Hamcrest, and Mockito libraries. In the Spring project, we should add all these libraries as dependencies. However, in Spring Boot, we only 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 s, see the Spring documentation. Follow the official account Java technology stack reply boot to get a complete Spring Boot tutorial.
2. MVC configuration
Let's take a look at the configuration required for Spring and Spring Boot to create JSP Web applications.
Spring needs to define scheduler servlet s, mappings, and other support configurations. We can use web XML file or Initializer class to complete this operation:
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 views 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 add a Web launcher, Spring Boot only needs to configure a few properties in the application configuration file to complete the above operations:
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
All the above Spring configurations are automatically included by adding a Boot web starter through a process called auto configuration.
This means that Spring Boot will view the dependencies, properties and beans existing in the application, and configure the properties and beans according to these dependencies. Of course, if we want to add our own custom configuration, the Spring Boot auto configuration will be returned.
3. Configure 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 the thymeleaf-spring5 dependency and some configurations 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 only requires a dependency of spring boot starter Thymeleaf 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, and Spring Boot will automatically display them.
4. Spring Security configuration
For simplicity, we use the framework's default HTTP Basic authentication. Let's first look at the dependencies and configurations required to enable Security using Spring.
Spring first needs to rely on the 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, Spring Boot requires these dependencies for it to work. However, we only need to define the dependency of Spring Boot starter security, because this will automatically add all relevant dependencies to the classpath.
The security configuration in Spring Boot is the same as above. Follow the official account Java technology stack reply boot to get a complete Spring Boot tutorial.
Application boot configuration
The basic difference between application boot in Spring and Spring Boot is servlet.
Spring uses web XML or SpringServletContainerInitializer as its boot entry point.
Spring Boot only uses the Servlet 3 function to boot the application. Let's learn more about it
1. Spring boot configuration
Spring supports traditional web XML boot mode and the latest Servlet 3+ method.
Configure web Steps for XML method startup
1) Servlet container (server) reads web xml;
2)web. The DispatcherServlet defined in XML is instantiated by the container;
3) DispatcherServlet reads WEB-INF / {servletname} -servlet XML to create WebApplicationContext.
Finally, the DispatcherServlet registers the bean s defined in the application context.
Spring startup steps using Servlet 3+ method
The container searches for classes that implement ServletContainerInitializer and executes SpringServletContainerInitializer to find WebApplicationInitializer that implements all classes.
WebApplicationInitializer creates a dispatcher servlet with an XML or context @Configuration class and a previously created context.
2. SpringBoot boot 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, Spring Boot uses an embedded container 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 beans from the application context to the embedded servlet container.
Another feature of Spring Boot is that it automatically scans all classes in the same package or components in sub packages of Main classes.
Spring Boot provides a way to deploy it to an external container. We just need to extend SpringBootServletInitializer:
/** * War deploy */ 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 finds manifest The main class and SpringBootServletInitializer defined in the MF file will be responsible for binding servlets, filters and servletcontextinitializers.
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 in terms of deployment, these frameworks are very different. For example, the Spring Boot Maven plug-in provides Spring Boot support in Maven. It also allows you to package executable jar or war packages and run applications in place.
Some advantages of Spring Boot over Spring in the deployment environment include:
-
Provide embedded container support
-
Run jar independently with the command java -jar
-
When deploying in an external container, you can choose to exclude dependencies to avoid potential jar conflicts
-
Flexible options for specifying configuration files during deployment
-
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.
Learning notes and interview questions of spring series, including spring interview questions, spring cloud interview questions, spring boot interview questions, spring tutorial notes, spring boot tutorial notes, and 2020 Java interview manual. A total of 1184 pages of PDF documents have been sorted out.
Pay attention to the official account: programmer Bai Nannan obtained the spring family bucket information of 1184 page PDF document.