Spring 和 Spring Boot 的區別是什麼?

概述

對於 SpringSpringBoot到底有什麼區別,我聽到了不少答案,剛開始邁入學習 SpringBoot的我當時也是一頭霧水,隨着經驗的積累、我慢慢理解了這兩個框架到底有什麼區別,相信對於用了 SpringBoot好久的同窗來講,還不是很理解 SpringBoot到底和 Spring有什麼區別,看完文章中的比較,或許你有了不一樣的答案和見解!html

什麼是Spring

做爲 Java開發人員,你們都 Spring都不陌生,簡而言之, Spring框架爲開發 Java應用程序提供了全面的基礎架構支持。它包含一些很好的功能,如依賴注入和開箱即用的模塊,如: 
SpringJDBC、SpringMVC、SpringSecurity、SpringAOP、SpringORM、SpringTest,這些模塊縮短應用程序的開發時間,提升了應用開發的效率例如,在 JavaWeb開發的早期階段,咱們須要編寫大量的代碼來將記錄插入到數據庫中。可是經過使用 SpringJDBC模塊的 JDBCTemplate,咱們能夠將操做簡化爲幾行代碼。java

什麼是Spring Boot

SpringBoot基本上是 Spring框架的擴展,它消除了設置 Spring應用程序所需的 XML配置,爲更快,更高效的開發生態系統鋪平了道路。web

SpringBoot中的一些特徵:spring

一、建立獨立的 Spring應用。
二、嵌入式 TomcatJettyUndertow容器(無需部署war文件)。
三、提供的 starters 簡化構建配置
四、儘量自動配置 spring應用。
五、提供生產指標,例如指標、健壯檢查和外部化配置
六、徹底沒有代碼生成和 XML配置要求數據庫

從配置分析

Maven依賴

首先,讓咱們看一下使用Spring建立Web應用程序所需的最小依賴項安全

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

與Spring不一樣,Spring Boot只須要一個依賴項來啓動和運行Web應用程序:服務器

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

在進行構建期間,全部其餘依賴項將自動添加到項目中。架構

另外一個很好的例子就是測試庫。咱們一般使用 SpringTestJUnitHamcrestMockito庫。在 Spring項目中,咱們應該將全部這些庫添加爲依賴項。可是在 SpringBoot中,咱們只須要添加 spring-boot-starter-test依賴項來自動包含這些庫。mvc

Spring Boot爲不一樣的Spring模塊提供了許多依賴項。一些最經常使用的是:app

spring-boot-starter-data-jpa spring-boot-starter-security spring-boot-starter-test spring-boot-starter-web spring-boot-starter-thymeleaf

有關 starter的完整列表,請查看Spring文檔。

MVC配置

讓咱們來看一下 SpringSpringBoot建立 JSPWeb應用程序所需的配置。

Spring須要定義調度程序 servlet,映射和其餘支持配置。咱們可使用 web.xml 文件或 Initializer類來完成此操做:

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("/");
    }
}

還須要將 @EnableWebMvc註釋添加到 @Configuration類,並定義一個視圖解析器來解析從控制器返回的視圖:

@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;
    }
}

再來看 SpringBoot一旦咱們添加了 Web啓動程序, SpringBoot只須要在 application配置文件中配置幾個屬性來完成如上操做:

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

上面的全部Spring配置都是經過一個名爲auto-configuration的過程添加 Bootweb starter來自動包含的。

這意味着 SpringBoot將查看應用程序中存在的依賴項,屬性和 bean,並根據這些依賴項,對屬性和 bean進行配置。固然,若是咱們想要添加本身的自定義配置,那麼 SpringBoot自動配置將會退回。

配置模板引擎

如今咱們來看下如何在Spring和Spring Boot中配置Thymeleaf模板引擎。

Spring中,咱們須要爲視圖解析器添加 thymeleaf-spring5依賴項和一些配置:

@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);
    }
}

SpringBoot1X只須要 spring-boot-starter-thymeleaf的依賴項來啓用 Web應用程序中的 Thymeleaf支持。   可是因爲 Thymeleaf3.0中的新功能,咱們必須將 thymeleaf-layout-dialect 添加爲 SpringBoot2XWeb應用程序中的依賴項。配置好依賴,咱們就能夠將模板添加到 src/main/resources/templates文件夾中, SpringBoot將自動顯示它們。

Spring Security 配置

爲簡單起見,咱們使用框架默認的 HTTPBasic身份驗證。讓咱們首先看一下使用 Spring啓用 Security所需的依賴關係和配置。

Spring首先須要依賴 spring-security-webspring-security-config 模塊。接下來, 咱們須要添加一個擴展 WebSecurityConfigurerAdapter的類,並使用 @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();
    }
}

這裏咱們使用 inMemoryAuthentication來設置身份驗證。一樣, SpringBoot也須要這些依賴項才能使其工做。可是咱們只須要定義 spring-boot-starter-security的依賴關係,由於這會自動將全部相關的依賴項添加到類路徑中。

SpringBoot中的安全配置與上面的相同

應用程序啓動引導配置

SpringSpringBoot中應用程序引導的基本區別在於 servletSpring使用 web.xmlSpringServletContainerInitializer做爲其引導入口點。SpringBoot僅使用 Servlet3功能來引導應用程序,下面讓咱們詳細來了解下

Spring 引導配置

Spring支持傳統的 web.xml引導方式以及最新的 Servlet3+方法。

配置 web.xml方法啓動的步驟

Servlet容器(服務器)讀取 web.xml

web.xml中定義的 DispatcherServlet由容器實例化

DispatcherServlet經過讀取 WEB-INF/{servletName}-servlet.xml來建立 WebApplicationContext。最後, DispatcherServlet註冊在應用程序上下文中定義的 bean

使用 Servlet3+方法的 Spring啓動步驟

容器搜索實現 ServletContainerInitializer的類並執行 SpringServletContainerInitializer找到實現全部類 WebApplicationInitializer`WebApplicationInitializer建立具備XML或上下文 @ConfigurationWebApplicationInitializer建立 DispatcherServlet`與先前建立的上下文。

SpringBoot 引導配置

Spring Boot應用程序的入口點是使用@SpringBootApplication註釋的類

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

默認狀況下, SpringBoot使用嵌入式容器來運行應用程序。在這種狀況下, SpringBoot使用 publicstaticvoidmain入口點來啓動嵌入式 Web服務器。此外,它還負責將 ServletFilterServletContextInitializerbean從應用程序上下文綁定到嵌入式 servlet容器。SpringBoot的另外一個特性是它會自動掃描同一個包中的全部類或 Main類的子包中的組件。

SpringBoot提供了將其部署到外部容器的方式。咱們只須要擴展 SpringBootServletInitializer便可:

/**
 * War部署
 */
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());
    }
}

這裏外部 servlet容器查找在war包下的 META-INF文件夾下MANIFEST.MF文件中定義的 Main-classSpringBootServletInitializer將負責綁定 ServletFilterServletContextInitializer

打包和部署

最後,讓咱們看看如何打包和部署應用程序。這兩個框架都支持 MavenGradle等通用包管理技術。可是在部署方面,這些框架差別很大。例如,Spring Boot Maven插件在 Maven中提供 SpringBoot支持。它還容許打包可執行 jarwar包並 就地運行應用程序。

在部署環境中 SpringBoot 對比 Spring的一些優勢包括:

一、提供嵌入式容器支持
二、使用命令_java -jar_獨立運行jar
三、在外部容器中部署時,能夠選擇排除依賴關係以免潛在的jar衝突
四、部署時靈活指定配置文件的選項
五、用於集成測試的隨機端口生成

結論

簡而言之,咱們能夠說 SpringBoot只是 Spring自己的擴展,使開發,測試和部署更加方便。

相關文章
相關標籤/搜索