雲栖号資訊:【 點選檢視更多行業資訊】
在這裡您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來!
概述
對于 Spring和 SpringBoot到底有什麼差別,我聽到了很多答案,剛開始邁入學習 SpringBoot的我當時也是一頭霧水,随着經驗的積累、我慢慢了解了這兩個架構到底有什麼差別,相信對于用了 SpringBoot很久的同學來說,還不是很了解 SpringBoot到底和 Spring有什麼差別,看完文章中的比較,或許你有了不同的答案和看法!
什麼是Spring
作為 Java開發人員,大家都 Spring都不陌生,簡而言之, Spring架構為開發 Java應用程式提供了全面的基礎架構支援。它包含一些很好的功能,如依賴注入和開箱即用的子產品,如:
SpringJDBC、SpringMVC、SpringSecurity、SpringAOP、SpringORM、SpringTest,這些子產品縮短應用程式的開發時間,提高了應用開發的效率例如,在 JavaWeb開發的早期階段,我們需要編寫大量的代碼來将記錄插入到資料庫中。但是通過使用 SpringJDBC子產品的 JDBCTemplate,我們可以将操作簡化為幾行代碼。
什麼是Spring Boot
SpringBoot基本上是 Spring架構的擴充,它消除了設定 Spring應用程式所需的 XML配置,為更快,更高效的開發生态系統鋪平了道路。
SpringBoot中的一些特征:
1、建立獨立的 Spring應用。
2、嵌入式 Tomcat、 Jetty、 Undertow容器(無需部署war檔案)。
3、提供的 starters 簡化建構配置
4、盡可能自動配置 spring應用。
5、提供生産名額,例如名額、健壯檢查和外部化配置
6、完全沒有代碼生成和 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>
在進行建構期間,所有其他依賴項将自動添加到項目中。
另一個很好的例子就是測試庫。我們通常使用 SpringTest, JUnit, Hamcrest和 Mockito庫。在 Spring項目中,我們應該将所有這些庫添加為依賴項。但是在 SpringBoot中,我們隻需要添加 spring-boot-starter-test依賴項來自動包含這些庫。
Spring Boot為不同的Spring子產品提供了許多依賴項。一些最常用的是:
spring-boot-starter-data-jpaspring-boot-starter-securityspring-boot-starter-testspring-boot-starter-webspring-boot-starter-thymeleaf
有關 starter的完整清單,請檢視Spring文檔。
- MVC配置
讓我們來看一下 Spring和 SpringBoot建立 JSPWeb應用程式所需的配置。
Spring需要定義排程程式 servlet,映射和其他支援配置。我們可以使用 web.xml 檔案或 Initializer類來完成此操作:
publicclass
MyWebAppInitializer
implements
WebApplicationInitializer
{
@Override
publicvoid
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
publicclass
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配置檔案中配置幾個屬性來完成如上操作:
spring.mvc.view.prefix=
/WEB-INF/
jsp/
spring.mvc.view.suffix=.jsp
上面的所有Spring配置都是通過一個名為auto-configuration的過程添加 Bootweb starter來自動包含的。
這意味着 SpringBoot将檢視應用程式中存在的依賴項,屬性和 bean,并根據這些依賴項,對屬性和 bean進行配置。當然,如果我們想要添加自己的自定義配置,那麼 SpringBoot自動配置将會退回。
配置模闆引擎
現在我們來看下如何在Spring和Spring Boot中配置Thymeleaf模闆引擎。
在 Spring中,我們需要為視圖解析器添加 thymeleaf-spring5依賴項和一些配置:
@Configuration
@EnableWebMvc
publicclass
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
publicvoid
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-web和 spring-security-config 子產品。接下來, 我們需要添加一個擴充 WebSecurityConfigurerAdapter的類,并使用 @EnableWebSecurity注解:
@Configuration
@EnableWebSecurity
publicclass
CustomWebSecurityConfigurerAdapter
extends
WebSecurityConfigurerAdapter
{
@Autowired
publicvoid
configureGlobal(
AuthenticationManagerBuilder
auth)
throws
Exception
{
auth.inMemoryAuthentication()
.withUser(
"admin"
)
.password(passwordEncoder()
.encode(
"password"
))
.authorities(
"ROLE_ADMIN"
);
}
@Override
protectedvoid
configure(
HttpSecurity
http)
throws
Exception
{
http.authorizeRequests()
.anyRequest().authenticated()
.
and
()
.httpBasic();
}
@Bean
public
PasswordEncoder
passwordEncoder() {
returnnew
BCryptPasswordEncoder
();
}
}
這裡我們使用 inMemoryAuthentication來設定身份驗證。同樣, SpringBoot也需要這些依賴項才能使其工作。但是我們隻需要定義 spring-boot-starter-security的依賴關系,因為這會自動将所有相關的依賴項添加到類路徑中。
SpringBoot中的安全配置與上面的相同 。
- 應用程式啟動引導配置
Spring和 SpringBoot中應用程式引導的基本差別在于 servlet。Spring使用 web.xml 或 SpringServletContainerInitializer作為其引導入口點。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或上下文 @Configuration類 WebApplicationInitializer建立 DispatcherServlet與先前建立的上下文。
- SpringBoot 引導配置
Spring Boot應用程式的入口點是使用@SpringBootApplication注釋的類
@SpringBootApplication
publicclass
Application
{
publicstaticvoid
main(
String
[] args) {
SpringApplication
.run(
Application
.
class
, args);
}
}
預設情況下, SpringBoot使用嵌入式容器來運作應用程式。在這種情況下, SpringBoot使用 publicstaticvoidmain入口點來啟動嵌入式 Web伺服器。此外,它還負責将 Servlet, Filter和 ServletContextInitializerbean從應用程式上下文綁定到嵌入式 servlet容器。SpringBoot的另一個特性是它會自動掃描同一個包中的所有類或 Main類的子包中的元件。
SpringBoot提供了将其部署到外部容器的方式。我們隻需要擴充 SpringBootServletInitializer即可:
/**
* War部署
*
* @author SanLi
* Created by [email protected] on 2018/4/15
*/
publicclass
ServletInitializer
extends
SpringBootServletInitializer
{
@Override
protected
SpringApplicationBuilder
configure(
SpringApplicationBuilder
application) {
return
application.sources(
Application
.
class
);
}
@Override
publicvoid
onStartup(
ServletContext
servletContext)
throws
ServletException
{
super
.onStartup(servletContext);
servletContext.addListener(
new
HttpSessionEventPublisher
());
}
}
這裡外部 servlet容器查找在war包下的 META-INF檔案夾下MANIFEST.MF檔案中定義的 Main-class, SpringBootServletInitializer将負責綁定 Servlet, Filter和 ServletContextInitializer。
- 打包和部署
最後,讓我們看看如何打包和部署應用程式。這兩個架構都支援 Maven和 Gradle等通用包管理技術。但是在部署方面,這些架構差異很大。例如,Spring Boot Maven插件在 Maven中提供 SpringBoot支援。它還允許打包可執行 jar或 war包并 就地運作應用程式。
在部署環境中 SpringBoot 對比 Spring的一些優點包括:
1、提供嵌入式容器支援
2、使用指令java -jar獨立運作jar
3、在外部容器中部署時,可以選擇排除依賴關系以避免潛在的jar沖突
4、部署時靈活指定配置檔案的選項
5、用于內建測試的随機端口生成
結論
簡而言之,我們可以說 SpringBoot隻是 Spring本身的擴充,使開發,測試和部署更加友善。
【雲栖号線上課堂】每天都有産品技術專家分享!
課程位址:
https://yqh.aliyun.com/zhibo立即加入社群,與專家面對面,及時了解課程最新動态!
【雲栖号線上課堂 社群】
https://c.tb.cn/F3.Z8gvnK
原文釋出時間:2020-04-09
本文作者:樂傻驢
本文來自:“
網際網路架構師 微信公衆号”,了解相關資訊可以關注“
人工智能學家”