The simplified road from Spring MVC to Spring BOOT

background

From Servlet technology to Spring and Spring MVC, developing web applications has become easier and simpler. However, the many configurations of Spring and Spring MVC are sometimes prohibitive. I believe that friends who have experience in Spring MVC development can deeply appreciate this pain. Because even to develop a Hello-World web application, we need to import various dependencies in the pom file, write web.xml, spring.xml, springmvc.xml configuration files, etc. Especially when we need to import a large number of jar package dependencies, we need to search for various jar package resources on the Internet. There may be various dependencies between each jar. At this time, we have to download the jar packages they depend on. Sometimes there are still jar packages. There are strict version requirements, so when we just want to develop a super simple web application of Hello-World, we spend a large part of the time on writing configuration files and importing jar package dependencies, which greatly affects Our development efficiency. So in order to simplify the complicated configuration of Spring, Spring Boot came into being. As the name of Spring Boot, one-click start, Spring Boot provides automatic configuration functions, providing us with out-of-the-box functions, allowing us to focus on the development of business logic. So how does Spring Boot simplify Spring MVC? What is the relationship between Spring Boot and Spring and Spring MVC? What are the new features of Spring Boot? Next, let's walk into the simplified road from Spring MVC to Spring Boot, maybe you can find these answers.

Spring vs Spring MVC vs Spring Boot

  • Spring Boot is not in competition with Spring and Spring MVC. Spring Boot makes it easier for us to use Spring and Spring MVC

Spring FrameWork

  • The core problem that Spring FrameWork solves is what is the most important feature of the Spring framework is dependency injection, the core of all Spring modules is dependency injection (DI) or inversion of control (IOC). Why is it important, because when we use DI or IOC, we can decouple the application. Let's look at a simple example:

Example without dependency injection:

@RestController
public class WelcomeController {

    private WelcomeService service = new WelcomeService();

	@RequestMapping("/welcome")
	public String welcome() {
		return service.retrieveWelcomeMessage();
	}
}

WelcomeService service = new WelcomeService(); 意味着WelcomeController类与WelcomeService类紧密结合在一起,耦合度高。

Example using dependency injection:

@Component
public class WelcomeService {
    //Bla Bla Bla
}

@RestController
public class WelcomeController {

    @Autowired
    private WelcomeService service;

	@RequestMapping("/welcome")
	public String welcome() {
		return service.retrieveWelcomeMessage();
	}
}

依赖注入使世界看起来更简单,我们让Spring 框架做了辛勤的工作:
@Component:我们告诉Spring框架-嘿,这是一个你需要管理的bean
@Autowired:我们告诉Spring框架-嘿,找到这个特定类型的正确匹配并自动装入它

What else can Spring solve

1. Does Duplicate Code
Spring Framework stop Dependency Injection (DI)? No, it develops many Spring modules on the core concept of Dependency Injection (DI):

  • Spring JDBC
  • Spring MVC
  • Spring AOP
  • Spring ORM
  • Spring Test
  • ...
    consider Spring JDBC, do these modules bring new functionality? No, we can use Java code to complete these tasks. So what do they bring us? They bring about simple abstractions whose purpose is to:
  1. Reduce boilerplate code/reduce duplication
  2. Facilitates decoupling/increases unit testability Example: Compared to traditional JDBC, we need to write much less code with Spring JDBC.

2. Good integration with other frameworks
Spring framework doesn't try to solve problems already solved, all it does is provide perfect integration with frameworks that provide great solutions.

  • Hibernate
  • IBatis
  • JUnit
  • ...

Spring MVC

  • The core problem that the Spring MVC framework solves is what the Spring MVC framework provides for a decoupled way of developing web applications. Through simple concepts such as DispatcherServlet, ModelAndView, View Resolver, etc., web application development becomes easier.

Why you need Spring Boot

Spring based applications have a lot of configuration. When we use Spring MVC, we need to configure component scan, scheduler servlet, view resolver, etc:

视图解析器配置:
  <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
  </bean>
  
  <mvc:resources mapping="/webjars/**" location="/webjars/"/>
  
  前端调度器的典型配置:
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/todo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
当我们使用Hibernate / JPA时,我们需要配置一个数据源,一个实体管理器工厂,一个事务管理器以及许多其他事物:
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${db.driver}" />
        <property name="jdbcUrl" value="${db.url}" />
        <property name="user" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <jdbc:initialize-database data-source="dataSource">
        <jdbc:script location="classpath:config/schema.sql" />
        <jdbc:script location="classpath:config/data.sql" />
    </jdbc:initialize-database>

    <bean
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        id="entityManagerFactory">
        <property name="persistenceUnitName" value="hsql_pu" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

Problems that Spring Boot solves

1. Spring Boot auto-configuration
Spring introduces a new thought process: Can we get smarter? Can we auto-configure some beans when a spring mvc jar is added to the application?

  1. What about auto-configuring the datasource when the Hibernate jar is on the classpath?
  2. What about auto-configuring the Dispatcher Servlet when Spring MVC jars are on the classpath?
  • Spring Boot looks at the frameworks on the CLASSPATH that need to write configuration for this application. Based on these, Spring Boot provides the basic configuration of these frameworks - this is automatic configuration.

2. Spring Boot Starter Projects
Suppose we want to develop a web application. First, we need to decide which framework we want to use, which version of the framework to use and how to wire them together. All web applications have similar needs Listed below are some of the dependencies we use in Spring MVC. These include Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (for server-side validation using the Java Validation API), and Log4j (for logging). When creating, we have to choose compatible versions of all these frameworks:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.2.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.2.Final</version>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
    
  • What is a Starter
Starter是一套方便的依赖描述符,可以包含在应用程序中。
你可以获得所需的所有Spring及相关技术的一站式服务,而无需搜索示例代码并复制依赖描述符的粘贴负载。
例如,如果你想开始使用Spring和JPA来访问数据库,只需在你的项目中包含spring-boot-starter-data-jpa依赖项就好。

Let's look at an example of Starter - Spring-Boot-Starter-Web

Spring-Boot-Starter-Web依赖:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

The following screenshots show the different dependencies added to our application:

Any typical web application will use all these dependencies. Spring Boot Starter Web comes prepackaged with these. As developers, we don't need to worry about these dependencies or compatible versions.

3. Spring Boot Starter Project Options
Just like Spring Boot Starter Web, Starter projects help us quickly get started developing specific types of applications:

  • spring-boot-starter-web-services - SOAP Web服务
  • spring-boot-starter-web - Web and RESTful applications
  • spring-boot-starter-test - Unit and integration tests
  • spring-boot-starter-data-jpa - 带有Hibernate的Spring Data JPA
  • spring-boot-starter-cache - Enable Spring Framework's caching support
  • ...

What is Spring Boot autoconfiguration

It has been introduced initially and will be introduced in detail here.
When we start the Spring Boot application, we can see some important messages in the logs.

Mapping servlet: 'dispatcherServlet' to [/]

Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)

Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

The above log statement shows the behavior of Spring Boot Auto Configuration.
As soon as we add the Spring Boot Starter Web dependency to our application, Spring Boot AutoConfiguration finds that Spring MVC is on the classpath and it automatically configures dispatcherServlet, a default error page and webjars.
If you add the Spring Boot DataJPA Starter dependency, Spring Boot AutoConfiguration will automatically configure the datasource and Entity Manager

Where is Spring Boot Auto Configuration implemented

All auto-configuration logic is implemented in spring-boot-autoconfigure.jar. All auto-configuration logic for mvc, data, and other frameworks lives in a single jar.

The important file in spring-boot-autoconfigure.jar is /META-INF/spring.factories, this file; lists all auto-configuration classes started under the EnableAutoConfiguration key. Some important configuration classes are listed below:

 

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\

View automatic configuration

Turn on debug logging Turn on debug logging
in application.properties:

logging.level.org.springframework: DEBUG

When the program is started, the auto-configuration log information is printed

Summarize

The emergence of Spring Boot itself is to reduce the threshold of Web development, so that developers can focus on business development without wasting time outside business development. So far, the simplified road from Spring MVC to Spring Boot is over.


Author: Beyondlcg
Link: https://juejin.im/post/5aa22d1f51882555677e2492
Source: Nuggets
The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326151837&siteId=291194637