Spring vs Spring Boot

在开始接触Spring家族的组件时,搞不清楚家族成员之间的关系会让学习过程盲目,参考Spring Boot vs Spring MVC vs Spring - How do they compare?总结了Spring, Spring MVC, Spring Boot的关系。

Spring Framework解决了什么问题?

1. 应用程序的强耦合

Most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.

应用依赖注入方法,可以开发出弱耦合的应用,方便测试和维护。

一个关于测试的例子:

  • 没有应用依赖注入时
    下面的代码中,WelcomeService 在WelcomeController类中实例化,那么WelcomeService 就和WelcomeController形成了强耦合关系。这是如果进行测试,我们Mock了WelcomeService,但此时如果要Mock WelcomeController 就会很麻烦,因为已经有了WelcomeService,但是在代码中还要实例化另一个WelcomeService,两者冲突。
@RestController
public class WelcomeController {

    private WelcomeService service = new WelcomeService();

    @RequestMapping("/welcome")
    public String welcome() {
        return service.retrieveWelcomeMessage();
    }
}
  • 应用依赖注入时
    该段代码中:
    @Component注释的作用:告诉Spring这里有一个Bean需要他的容器进行管理
    @Autowired注释的作用:告诉Spring,这里的代码需要找一个匹配的Bean覆盖这里的代码(就是上面提到的那个Bean),这里的代码只是为了程序的完整性和作为定位点而存在。
    这时代码的耦合程度较低,可以方便的Mock WelcomeService,这时Mock WelcomeController 也不影响。
@Component
public class WelcomeService {
    //Bla Bla Bla
}

@RestController
public class WelcomeController {

    @Autowired
    private WelcomeService service;

    @RequestMapping("/welcome")
    public String welcome() {
        return service.retrieveWelcomeMessage();
    }
}
2. 重复的代码

开发者们在依赖注入思想的指导下,开发了许多有效的Spring模块:

  • Spring JDBC
  • Spring MVC
  • Spring AOP
  • Spring ORM
  • Spring JMS
  • Spring Test

以Spring JMS和Spring JDBC为例,这些模块并没有带来新的功能,实现的功能都可以用J2EE或是JEE实现。这些模块的作用是通过抽象实现以下目的:

  • 减少Boilerplate Code(重复、冗长但又不得不写的代码)/减少重复(Reduce Boilerplate Code/ Reduce Duplication)
  • 促进解耦/增加单位可测性(Promote Decoupling/ Increase Unit Testablity)
3. 与其他框架协同使用

Spring可以与其他框架有良好的集成:

  • Hibernate for ORM
  • iBatis for Object Mapping
  • JUnit & Mockito for Unit Testing
Spring MVC解决了什么问题?

Spring MVC提供可开发弱耦合的网页应用的方法,使用Spring MVC提供的Dispatcher Servlet, ModelAndView and View Resolver概念,可以让开发过程更加简单。

为什么需要 Spring Boot?

Spring Boot offers a fast way to build applications. It looks at your classpath and at beans you have configured, makes reasonable assumptions about what you’re missing, and adds it. With Spring Boot you can focus more on business features and less on infrastructure.

SpringBoot官方文档上对SpringBoot作用的描述:Spring Boot是写Java应用的工具,目标是让开发过程更多关注在业务上,不必花费太多精力在基础架构上。实现这个过程用到的方法如下:

1. Auto Configuration

基于Spring的应用需要大量的配置过程,例如,在使用Spring MVC开发网页应用的时候,需要配置 component scan, dispatcher servlet, view resolver, web jars(for delivering static content)等等。

Spring configuration consists of at least one and typically more than one bean definition that the container must manage.
1. XML-based configuration metadata shows these beans configured as elements inside a top-level element.
2. Java configuration typically uses @Bean annotated methods within a @Configuration class.

  <!-繁杂的配置过程例子-->
  <!--配置resolver,web jars-->
  <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>
        <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时,配置dataSource,manager factory, transaction manager -->
    <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"/>

SpringBoot可以提供检查项目组织的路径和配置的Beans的服务,针对这些繁杂的配置,考虑到Spring Framework中CLASSPATH的作用和应用中已有的配置,提供了应用中需要的基础配置,称作Auto Configuration,Spring Boot的配置过程可用下图表示:
Spring boot 配置

2. Starter

以网页应用为例,我们需要选择合适版本的框架及其合适版本的组件。考虑到绝大部分网页应用有许多功能都是相似的,大多时候使用的组件是相同的,如 Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (验证) and Log4j (日志)。这时需要我们选择组件的版本:

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

这个过程繁琐,为此Staters应用而生。Spring boot文档中对Starter的说明:

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.

如果用Spring Boot做开发, 应用Starter可以表示为

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

下图中的依赖将会自动添加
Dependency

这些依赖可以分为以下几类:

  • Spring - core, beans, context, aop
  • Web MVC - (Spring MVC)
  • Jackson - for JSON Binding
  • Validation - Hibernate Validator, Validation API
  • Embedded Servlet Container - Tomcat
  • Logging - logback, slf4

通过Starter管理依赖相比于Spring Framework十分简单。
常用的Starter有:

  • spring-boot-starter-web-services - SOAP Web Services
  • spring-boot-starter-web - Web & RESTful applications
  • spring-boot-starter-test - Unit testing and Integration Testing
  • spring-boot-starter-jdbc - Traditional JDBC
  • spring-boot-starter-hateoas - Add HATEOAS features to your services
  • spring-boot-starter-security - Authentication and Authorization using Spring Security
  • spring-boot-starter-data-jpa - Spring Data JPA with Hibernate
  • spring-boot-starter-cache - Enabling Spring Framework’s caching support
  • spring-boot-starter-data-rest - Expose Simple REST Services using Spring Data REST
3.其它功能

Spring Boot也提供了一些Starter

  • spring-boot-starter-actuator - To use advanced features like monitoring & tracing to your application out of the box
  • spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat - To pick your specific choice of Embedded Servlet Container
  • spring-boot-starter-logging - For Logging using logback
  • spring-boot-starter-log4j2 - Logging using Log4j2

这些组件可以让开发者可以在短时间内就提供产评级的应用:

  • Actuator:监控追踪
  • Embedded Server Integrations:嵌入式服务器集成
  • Default Error Handling:异常处理

猜你喜欢

转载自blog.csdn.net/sinat_34763749/article/details/80572279