Author: Happy silly donkey

uee.me/cNDC8

An overview of the

As for the difference between Spring and SpringBoot, I have heard many answers. At the beginning of learning SpringBoot, I was also confused. With the accumulation of experience, I gradually understood the difference between the two frameworks. Still not quite understand SpringBoot and Spring exactly what difference, read the article comparison, perhaps you have a different answer and view!

What is the 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:

SpringJDBC, SpringMVC, SpringSecurity, SpringAOP, SpringORM, SpringTest, these modules shorten the development time of application programs and improve the efficiency of application development. For example, in the early stage of JavaWeb development, We need to write a lot of code to insert records into the database. But by using the JDBCTemplate of the SpringJDBC module, we can simplify this to a few lines of code.

What is Spring Boot

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

SpringBootSome characteristics of:

** Create a separate Spring application. ** embedded Tomcat, Jetty, and Undertow containers (war file is not required). **4. ** Automatically configure spring apps as much as possible. **5, ** Provides production metrics, such as metrics, robustness, and external configuration **6, ** has no code generation and XML configuration requirements at all

Analysis by configuration

Maven rely on

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

  1. <dependency>

  2. <groupId>org.springframework</groupId>

  3. <artifactId>spring-web</artifactId>

  4. < version > 5.1.0. RELEASE < / version >

  5. </dependency>

  6. <dependency>

  7. <groupId>org.springframework</groupId>

  8. <artifactId>spring-webmvc</artifactId>

  9. < version > 5.1.0. RELEASE < / version >

  10. </dependency>

Unlike Spring, Spring Boot requires only one dependency to start and run a Web application:

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-web</artifactId>

  4. < version > 2.0.6. RELEASE < / version >

  5. </dependency>

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

Another good example is test libraries. We usually use SpringTest, JUnit, Hamcrest and Mockito libraries. In our Spring project, we should add all of these libraries as dependencies. But in SpringBoot, 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-bo ot-starter-thymeleaf

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

MVC configuration

Let’s take a lookSpringandSpringBootcreateJSPWebConfiguration 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:

  1. public class MyWebAppInitializer implements WebApplicationInitializer {

  2. @Override

  3. public void onStartup(ServletContext container) {

  4. AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

  5. context.setConfigLocation("com.pingfangushi");

  6. container.addListener(new ContextLoaderListener(context));

  7. ServletRegistration.Dynamic dispatcher = container

  8. .addServlet("dispatcher", new DispatcherServlet(context));

  9. dispatcher.setLoadOnStartup(1);

  10. dispatcher.addMapping("/");

  11. }

  12. }

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:

  1. @EnableWebMvc

  2. @Configuration

  3. public class ClientWebConfig implements WebMvcConfigurer {

  4. @Bean

  5. public ViewResolver viewResolver() {

  6. InternalResourceViewResolver bean

  7. = new InternalResourceViewResolver();

  8. bean.setViewClass(JstlView.class);

  9. bean.setPrefix("/WEB-INF/view/");

  10. bean.setSuffix(".jsp");

  11. return bean;

  12. }

  13. }

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

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

  2. spring.mvc.view.suffix=.jsp

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

This means that SpringBoot 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, SpringBoot automatic configuration will fall back.

Configuring 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:

  1. @Configuration

  2. @EnableWebMvc

  3. public class MvcWebConfig implements WebMvcConfigurer {

  4. @Autowired

  5. private ApplicationContext applicationContext;

  6. @Bean

  7. public SpringResourceTemplateResolver templateResolver() {

  8. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

  9. templateResolver.setApplicationContext(applicationContext);

  10. templateResolver.setPrefix("/WEB-INF/views/");

  11. templateResolver.setSuffix(".html");

  12. return templateResolver;

  13. }

  14. @Bean

  15. public SpringTemplateEngine templateEngine() {

  16. SpringTemplateEngine templateEngine = new SpringTemplateEngine();

  17. templateEngine.setTemplateResolver(templateResolver());

  18. templateEngine.setEnableSpringELCompiler(true);

  19. return templateEngine;

  20. }

  21. @Override

  22. public void configureViewResolvers(ViewResolverRegistry registry) {

  23. ThymeleafViewResolver resolver = new ThymeleafViewResolver();

  24. resolver.setTemplateEngine(templateEngine());

  25. registry.viewResolver(resolver);

  26. }

  27. }

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. Configured rely on, we can add the template to the SRC/main/resources/templates folder, SpringBoot will automatically display them.

Spring Security configuration

For simplicity, we use the framework’s default HTTPBasic 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:

  1. @Configuration

  2. @EnableWebSecurity

  3. public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

  4. @Autowired

  5. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

  6. auth.inMemoryAuthentication()

  7. .withUser("admin")

  8. .password(passwordEncoder()

  9. .encode("password"))

  10. .authorities("ROLE_ADMIN");

  11. }

  12. @Override

  13. protected void configure(HttpSecurity http) throws Exception {

  14. http.authorizeRequests()

  15. .anyRequest().authenticated()

  16. .and()

  17. .httpBasic();

  18. }

  19. @Bean

  20. public PasswordEncoder passwordEncoder() {

  21. return new BCryptPasswordEncoder();

  22. }

  23. }

Here we use inMemoryAuthentication to set up authentication. SpringBoot also needs these dependencies for it to 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 SpringBoot is the same as above.

The application starts the boot configuration

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

Spring Boot Configuration

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

configurationweb.xmlMethod startup steps

The Servlet container (server) reads web.xml

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

DispatcherServlet creates the WebApplicationContext by reading web-INF /{servletName}-servlet.xml. Finally, the DispatcherServlet registers the beans defined in the application context

useServlet3+methodsSpringThe launch step

Container implemented search ServletContainerInitializer class and implement SpringServletContainerInitializer find all classes WebApplicationInitializer ` ` WebApplicationInitializer create a @ the Configuration classes WebApplicationInitializer create XML or context The DispatcherServlet with the previously created context.

SpringBoot boot configuration

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

  1. @SpringBootApplication

  2. public class Application {

  3. public static void main(String[] args) {

  4. SpringApplication.run(Application.class, args);

  5. }

  6. }

By default, SpringBoot uses an embedded container to run applications. In this case, SpringBoot uses the PublicStaticVoidMain entry point to launch the embedded Web server. In addition, it also is responsible for the Servlet Filter and ServletContextInitializerbean from the application context is bound to the embedded Servlet container. Another feature of SpringBoot is that it automatically scans all classes in the same package or components in subpackages of the Main class.

SpringBoot provides a way to deploy it to an external container. We only need to expand SpringBootServletInitializer:

  1. / * *

  2. * War deployment

  3. *

  4. * @author SanLi

  5. * Created by [email protected] on 2018/4/15

  6. * /

  7. public class ServletInitializer extends SpringBootServletInitializer {

  8. @Override

  9. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

  10. return application.sources(Application.class);

  11. }

  12. @Override

  13. public void onStartup(ServletContext servletContext) throws ServletException {

  14. super.onStartup(servletContext);

  15. servletContext.addListener(new HttpSessionEventPublisher());

  16. }

  17. }

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 SpringBoot Maven plug-in provides SpringBoot support in Maven. It also allows you to package an executable JAR or WAR package and run the application in place.

Some of SpringBoot’s advantages over Spring in a deployment environment include:

**1, ** provides embedded container support **2, ** command

java -jar

Run jars independently **3, ** When deployed in an external container, you can choose to exclude dependencies to avoid potential JAR conflicts **4, ** Flexible option to specify configuration files at deployment **5, ** Random port generation for integration testing

conclusion

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