Spring Boot的核心功能與使用優點?
核心功能:
1)Spring Boot項目爲獨立運行的spring項目,java -jar xx.jar
即可運行。
2)內嵌servlet容器(可以選擇內嵌: tomcat,jetty等服務器)。
3)提供了starter的pom配置簡化了maven的配置。
4)自動配置spring容器中的bean。當不滿足實際開發場景,可自定義bean的自動化配置。
5)準生產的應用監控(基於:ssh
,http
,telnet
對服務器運行的項目進行監控)。
6)Spring Boot無需做出xml配置,也不是通過代碼生成來實現(通過條件註解)。
使用優點:
1)快速搭建項目,與主流框架集成無需配置集成。內嵌服務容器,具有應用監控,開發部署方便,後期與雲計算平臺集成方便(docket)。
2)使用JavaConfig有助於避免使用XML。
3)避免大量的Maven導入和各種版本衝突。
4)沒有單獨的Web服務器需要。這意味着你不再需要啓動Tomcat
,Glassfish
或其他任何東西。
5)需要更少的配置因爲沒有web.xml文件。只需添加用@Configuration註釋的類,然後添加用@Bean註釋的方法,Spring將自動加載對象並像以前一樣對其進行管理。您甚至可以將@Autowired添加到bean方法中,以使 Spring 自動裝入需要的依賴關係中。
6)基於環境的配置使用這些屬性,您可以將您正在使用的環境傳遞到應用程序:-Dspring.profiles.active = {enviornment}
。在加載主應用程序屬性文件後,Spring將在(application{environment}.properties
)中加載後續的應用程序屬性文件。
什麼是Spring Boot項目中的自動配置與手動配置?如果需要手動配置該如何實現?.
1. 自動配置: Spring Boot項目默認支持很多框架的集成,添加組件即可。只需要: 針對application.properties
做出自動配置的屬性重寫即可完成,默認開啓。關注微信公衆號“Java精選”(w_z90110)。
舉例:
Spring Boot採用自動配置集成freemarker
模板引擎,前提: 構建spring boot項目。
1)引入模板組件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2)編寫Controller和freemarker模板,位於resources/templates
2. 手動配置: 手動自定義web組件,代替Spring Boot項目默認支持的組件與配置。
舉例:
採用手動配置參數,集成freemarker模板引擎.
1)前提: spring-boot-starter-web
引入;
2)編寫過程類似於springMVC;
3)額外的SpringMVC的容器配置:
默認基於spring boot的基本默認配置即可(需要修改: 位於application.properties
)。需要手動編寫類似於spring容器可以:
@Configuration Public class MVCConfiguration extends WebMvcConfigurerAdapter{ //視圖解析器默認地址爲: /resources , /static , /templates, /public,/META @Bean public InternalResourceViewResolver defaultResolver(){ InternalResourceViewResolver resourceViewResolver = new InternalResourceViewResolver(); resourceViewResolver.setPrefix("classpath:/templates/"); resourceViewResolver.setSuffix(".html"); return resourceViewResolver; } //解析視圖時,默認從以上地址中依次尋找視圖資源加載,如果自定義例如Freemarker模板視圖解析器的資源地址,那麼: @Bean public FreeMarkerViewResolver defaultResolver(){ FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver(); // freeMarkerViewResolver.setPrefix("classpath:/views/"); freeMarkerViewResolver.setSuffix(".html"); freeMarkerViewResolver.setContentType("text/html;charset=utf-8"); return freeMarkerViewResolver; } @Bean public FreeMarkerConfigurer freeMarkerConfigurer(){ FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPaths("classpath:/views/"); configurer.setDefaultEncoding("utf-8"); return configurer; } //如果不設置靜態資源目錄,默認: classpath: /static/ , classpath: /public/ , classpath: /resources/ , classpath: /META-INF/resources/ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/image/**").addResourceLocations("classpath:/static/image/"); registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/"); registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/"); } }
以上手動配置總結: 如果想要完全自定義,接管spring boot中的所有web配置,可以:
@Configuration: 創建mvc適配器子類的對象並綁定至spring容器中。 @EnableWebMvc: 掃描spring容器中的mvc適配器子類對象。 Public class MVCConfiguration extends WebMvcConfigurerAdapter{ 重寫方法即可. }
如何使用Maven來構建一個Spring Boot程序?
就像引入其他庫一樣,我們可以在Maven工程中加入Spring Boot依賴。然而,最好是從spring-boot-starter-parent
項目中繼承以及聲明依賴到Spring Boot starters
。這樣做可以使我們的項目可以重用Spring Boot的默認配置。
繼承spring-boot-starter-parent
項目依賴很簡 –我們只需要在pom.xml中定義一個parent節點:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent>
我們可以在Maven central中央倉庫中找到spring-boot-starter-parent的最新版本。
使用starter父項目依賴很方便,但是有時候不是可行的。關注微信公衆號“Java精選”(w_z90110)。如果我們公司都要求項目繼承標準 POM,我們就不能依賴Spring Boot starter
了。
這種情況,我們可以通過對POM元素的依賴管理來處理:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
最後可以添加Spring Boot starter
中一些依賴,之後就可以啓動項目了。
Spring Boot中如何禁用某些自動配置特性?
1)禁用某些自動配置特性使用@EnableAutoConfiguration
註解的exclude屬性來指明。例如,下面的代碼段是使DataSourceAutoConfiguration
無效:
// other annotations @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) public class MyConfiguration { }
2)使用@SpringBootApplication
註解,將@EnableAutoConfiguration
作爲元註解的項來啓用自動化配置,使用相同名字的屬性來禁用自動化配置:
// other annotations @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class MyConfiguration { }
3)使用spring.autoconfigure.exclude環境屬性來禁用自動化配置。
application.properties中的這項配置內容增加如下:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
如何將Spring Boot web應用程序部署爲JAR或WAR文件?
通常,將web應用程序打包成WAR文件,然後將它部署到另外的服務器上。這樣做使得我們能夠在相同的服務器上處理多個項目。當CPU和內存有限的情況下,這是一種最好的方法來節省資源。然而,事情發生了轉變。現在的計算機硬件相比起來已經比較廉價,並且現在的注意力大多轉移到服務器配置上。部署中對服務器配置的一個細小的失誤都會導致無可預料的災難發生。
Spring通過提供插件來解決這個問題,也就是spring-boot-maven-plugin
來打包web應用程序到一個額外的 JAR 文件當中。爲了引入這個插件,只需要在pom.xml
中添加一個plugin屬性:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>
有了這個插件,可以在執行package步驟後得到一個JAR包。這個JAR包包含所需的所有依賴以及一個嵌入的服務器。因此,無需擔心去配置一個額外的服務器了。可以通過運行一個普通的JAR包來啓動應用程序。
需要注意的是,爲了打包成JAR文件,pom.xml
中的packgaing
屬性必須定義爲jar:
<packaging>jar</packaging>
如果不定義這個元素默認值也是jar。
如果想構建一個WAR文件,將packaging
元素修改爲war:
<packaging>war</packaging>
並且需要將容器依賴從打包文件中移除:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
執行Maven的package步驟之後,我們得到一個可部署的WAR文件。
如何使用Spring Boot實現分頁和排序?
使用Spring Boot實現分頁非常簡單。使用Spring Data-JPA
可以實現將可分頁的傳遞給存儲庫方法。
Spring Boot中的監視器是什麼?如何監視所有Spring Boot微服務?
Spring boot actuator
是spring啓動框架中的重要功能之一。Spring Boot監視器可幫助您訪問生產環境中正在運行的應用程序的當前狀態。有幾個指標必須在生產環境中進行檢查和監控。即使一些外部應用程序可能正在使用這些服務來向相關人員觸發警報消息。監視器模塊公開了一組可直接作爲HTTP URL訪問的REST端點來檢查狀態。
Spring Boot 提供監視器端點以監控各個微服務的度量。這些端點對於獲取有關應用程序的信息(如它們是否已啓動)以及它們的組件(如數據庫等)是否正常運行很有幫助。但是,使用監視器的一個主要缺點或困難是必須單獨打開應用程序的知識點以瞭解其狀態或健康狀況。想象一下涉及50個應用程序的微服務,管理員將不得不擊中所有50個應用程序的執行終端。爲了幫助我們處理這種情況,可以集成開源項目,它建立在Spring Boot Actuator之上,它提供了一個Web UI,使我們能夠可視化多個應用程序的度量。
Spring Boot的Actuator是做什麼的?
本質上,Actuator
通過啓用production-ready
功能使得Spring Boot
應用程序變得更有生命力。這些功能允許我們對生產環境中的應用程序進行監視和管理。
集成Spring Boot Actuator到項目中需要做的只是將spring-boot-starter-actuator starter引入到POM.xml文件當中:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Spring Boot Actuaor
可以使用HTTP或者JMX endpoints
來瀏覽操作信息。大多數應用程序都是用HTTP,作爲endpoint的標識以及使用/actuator前綴作爲 URL路徑。
這裏有一些常用的內置endpoints Actuator:
Spring Boot項目web開發時如何集成web組件:servlet.filter.listener
?
自定義servlet(實現或繼承HttpServlet
),filter(實現或繼承Filter
),listener(實現或繼承ServletContextListener
)。
1)將以下組件直接提供在main()啓動類中,用於加載:
@Bean public ServletRegistrationBean servletRegistrationBean() { return new ServletRegistrationBean(new CustomServlet(), "/custom"); } @Bean public FilterRegistrationBean filterRegistrationBean() { return new FilterRegistrationBean(new CustomFilter(), servletRegistrationBean()); } @Bean public ServletListenerRegistrationBean<CustomListener> servletListenerRegistrationBean() { return new ServletListenerRegistrationBean<CustomListener>(new CustomListener()); }
2)啓動類實現ServletContextInitializer,重寫onStartup():
@SpringBootApplication public class SpringBootDemo102Application implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.addServlet("customServlet", new CustomServlet()).addMapping("/custom"); servletContext.addFilter("customFilter", new CustomFilter()) .addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "customServlet"); servletContext.addListener(new CustomListener()); } }
3)啓動類開啓掃描: @ServletComponentScan
工具組件採用註解進行加載:
@WebFilter(filterName = "customFilter", urlPatterns = "/*") @WebListener @WebServlet(name = "customServlet", urlPatterns = "/custom")
Spring Boot中的application.properties配置文件是什麼,有哪些配置?
application.properties
爲Spring Boot
項目中的一個系統自帶的全局屬性配置文件,提供默認屬性重寫的作用。可包含重寫系統tomcat
,spring
,springmvc
,mybatis
等諸多默認配置屬性。列舉部分如下:
#全局配置文件: 重寫視圖解析器的資源地址 #頁面默認前綴目錄 spring.mvc.view.prefix=/WEB-INF/jsp/ #響應頁面默認後綴 spring.mvc.view.suffix=.jsp #靜態資源目錄配置, spring.mvc.static-path-pattern=/static/** #默認支持的日誌記錄: #logging.config=classpath:logback.xml 加載單獨的日誌配置文件 logging.file=d:/test/log.log logging.level.org.springframework.web=DEBUG #tomcat服務器的配置: server.port=8081 server.servlet.context-path=/yoodb #提供jdbc的基本配置: spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/yoodb01?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.type=org.apache.commons.dbcp.BasicDataSource #提供mybatis的屬性配置: 掃描 mybatis.mapper-locations=classpath:mapper/*_mapper.xml
如何在Spring Boot中添加通用的JS代碼?
在源文件夾下創建一個名爲static的文件夾。之後把靜態的內容放在這裏面。
例如,yoodb.js的路徑是resources\static\js\yoodb.js
,可以參考它在jsp中的使用方法:
錯誤:HAL browser gives me unauthorized error - Full authenticaition is required to access this resource.
,該如何來修復這個錯誤呢?
兩種方式:
1)關閉安全驗證,打開application.properties
文件增加內容如下:
management.security.enabled:FALSE
2)在日誌中搜索密碼並傳遞至請求頭中
Spring和Spring Boot有什麼不同?
Spring框架提供多種特性使得web應用開發變得更簡便,包括依賴注入、數據綁定、切面編程、數據存取等。
但隨着時間推移,Spring生態變得越來越複雜了,並且應用程序所必須的配置文件也令人覺得可怕。這就是Spirng Boot派上用場的地方了–它使得Spring的配置變得更輕而易舉。
實際上,Spring是unopinionated
(予以配置項多,傾向性弱) 的,Spring Boot在平臺和庫的做法中更opinionated,使得我們更容易上手。
簡單總結兩條Spring Boot帶來的好處:
1)根據classpath中的artifacts的自動化配置應用程序;
2)提供非功能性特性例如安全和健康檢查給到生產環境中的應用程序。