Spring Boot 需要獨立的容器運行嗎?
可以不需要,內置了 Tomcat/ Jetty 等容器。通過pom.xml中導入依賴:
1
2
3
4
5
6
|
<!--spring-boot-starter-web:代表web模塊,在這個模塊中含了許多JAR包,-->
<!--有spring相關的jar,內置tomcat服務器,jackson等,這些web項目中常用的的功能都會自動引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
|
Spring Boot的核心註解是哪個?它主要由哪幾個註解組成的?
啓動類上面的註解是@SpringBootApplication
,它也是 Spring Boot 的核心註解,主要組合包含了以下 3 個註解:
@SpringBootConfiguration
@EnableAutoConfiguration
:打開自動配置的功能,也可以關閉某個自動配置的選項,如關閉數據源自動配置功能:@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
。
@ComponentScan
:Spring組件掃描。
如何理解Spring Boot中Starters含義?
Starters是什麼?
Starters可以理解爲啓動器,它包含了一系列可以集成到應用裏面的依賴包,你可以一站式集成Spring及其他技術,而不需要到處找示例代碼和依賴包。如你想使用Spring JPA訪問數據庫,只要加入spring-boot-starter-data-jpa
啓動器依賴就能使用了。Starters包含了許多項目中需要用到的依賴,它們能快速持續的運行,都是一系列得到支持的管理傳遞性依賴。
Starters命名?
Spring Boot官方的啓動器都是以spring-boot-starter-
命名的,代表了一個特定的應用類型。第三方的啓動器不能以spring-boot開頭命名,它們都被Spring Boot官方保留。一般一個第三方的應該這樣命名,像mybatis的mybatis-spring-boot-starter
。
Starters分類:
1)Spring boot提供的啓動器
啓動器名稱 | 功能描述 |
---|---|
spring-boot-starter | 核心模塊,包含自動配置支持、日誌庫和對 YAML 配置文件的支持。 |
spring-boot-starter-amqp | 通過 spring-rabbit 來支持AMQP協議(Advanced Message Queuing Protocol) |
spring-boot-starter-aop | 支持面向方面的編程即AOP,包括 spring-aop 和 AspectJ |
spring-boot-starter-artemis | 通過 Apache Artemis 支持 JMS 的 API(Java Message Service API) |
spring-boot-starter-batch | 支持 Spring Batch,包括 HSQLDB 數據庫 |
spring-boot-starter-cache | 支持 Spring 的 Cache 抽象 |
spring-boot-starter-cloud-connectors | 支持 Spring Cloud Connectors,簡化了在像 Cloud Foundry 或 Heroku 這樣的雲平臺上連接服務 |
spring-boot-starter-data-elasticsearch | 支持 ElasticSearch 搜索和分析引擎,包括 spring-data-elasticsearch |
spring-boot-starter-data-gemfire | 支持 GemFire 分佈式數據存儲,包括 spring-data-gemfire |
spring-boot-starter-data-jpa | 支持 JPA(Java Persistence API),包括 spring-data-jpa、spring-orm、Hibernate |
spring-boot-starter-data-solr | 支持 Apache Solr 搜索平臺,包括 spring-data-solr |
spring-boot-starter-data-mongodb | 支持MongoDB數據,包括spring-data-mongodb |
spring-boot-starter-data-rest | 通過 spring-data-rest-webmvc,支持通過 REST 暴露 Spring Data 數據倉庫 |
spring-boot-starter-redis | 支持 Redis 鍵值存儲數據庫,包括 spring-redis |
spring-boot-starter-data-jdbc | 支持 JDBC 訪問數據庫 |
spring-boot-starter-jta-atomikos | 通過 Atomikos 支持 JTA 分佈式事務處理 |
spring-boot-starter-jta-bitronix | 通過Bitronix支持JTA分佈式事務處理 |
spring-boot-starter-security | 支持 spring-security |
spring-boot-starter-test | 支持常規的測試依賴,包括JUnit、Hamcrest、Mockito以及spring-test模塊 |
spring-boot-starter-velocity | 支持Velocity模板引擎 |
spring-boot-starter-freemarker | 支持 FreeMarker 模板引擎 |
spring-boot-starter-thymeleaf | 支持 Thymeleaf 模板引擎,包括與Spring的集成 |
spring-boot-starter-mustache | 支持 Mustache 模板引擎 |
spring-boot-starter-web | 支持全棧式 Web 開發,包括 Tomcat 和 spring-webmvc |
spring-boot-starter-websocket | 支持 WebSocket 開發 |
spring-boot-starter-ws | 支持 Spring Web Services |
spring-boot-starter-groovy-templates | 支持 Groovy 模板引擎 |
spring-boot-starter-hateoas | 通過 spring-hateoas 支持基於 HATEOAS 的 RESTful Web 服務 |
spring-boot-starter-hornetq | 通過 HornetQ 支持 JMS |
spring-boot-starter-log4j | 支持 Log4J 日誌框架 |
spring-boot-starter-logging | 引入了 Spring Boot 默認的日誌框架 Logback |
spring-boot-starter-integration | 支持通用的 spring-integration 模塊 |
spring-boot-starter-jersey | 支持 Jersey RESTful Web 服務框架 |
spring-boot-starter-mail | 支持 javax.mail 模塊 |
spring-boot-starter-mobile | 支持 spring-mobile |
spring-boot-starter-social-facebook | 支持 spring-social-facebook |
spring-boot-starter-social-linkedin | 支持 spring-social-linkedin |
spring-boot-starter-social-twitter | 支持 spring-social-twitter |
spring-boot-starter-actuator | 增加了面向產品上線相關的功能,比如測量和監控 |
spring-boot-starter-remote-shell | 增加了遠程ssh shell的支持 |
spring-boot-starter-tomcat | 引入了 Spring Boot 默認的 HTTP 引擎 Tomcat |
spring-boot-starter-jetty | 引入了Jetty HTTP引擎(用於替換Tomcat) |
spring-boot-starter-undertow | 引入了Undertow HTTP引擎(用於替換Tomcat) |
4)其他第三方啓動器(略)
Spring Boot實現熱部署有哪幾種方式?
在Spring Boot實現代碼熱部署是一件很簡單的事情,代碼的修改可以自動部署並重新熱啓動項目。
1)引用devtools依賴
1
2
3
4
5
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>
true
</optional>
</dependency>
|
修改一個java類時就可以實現熱更新了。
2)自定義配置熱部署
以下配置用於自定義配置熱部署,可以不設置。
#熱部署開關,false即不啓用熱部署
1
|
spring.devtools.restart,enabled:
true
|
#指定熱部署的目錄
1
|
#spring.devtools.restart.additional-paths: src/main/java
|
#指定目錄不更新
1
|
spring.devtools.restart.exclude: test/**
|
3)Intellij Idea
工具修改實現熱部署
需要改以下兩個位置:
勾上自動編譯或者手動重新編譯
1
|
File > Settings > Compiler-Build Project automatically
|
註冊使用快捷鍵的方式:
1
|
ctrl + shift + alt + / > Registry > 勾選Compiler autoMake allow when app running
|
注意事項:
1)生產環境devtools將被禁用,如java -jar
方式或者自定義的類加載器等都會識別爲生產環境。
2)打包應用默認不會包含devtools,除非你禁用SpringBoot Maven
插件的excludeDevtools
屬性。
3)Thymeleaf無需配置 spring.thymeleaf.cache:false
,devtools默認會自動設置,參考完整屬性。
下面是devtools自動配置的完整源碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
@Order(Ordered.LOWEST_PRECEDENCE)
public
class
DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostProcessor {
private
static
final Map<String, Object> PROPERTIES;
static
{
Map<String, Object> devToolsProperties =
new
HashMap<>();
devToolsProperties.put(
"spring.thymeleaf.cache"
,
"false"
);
devToolsProperties.put(
"spring.freemarker.cache"
,
"false"
);
devToolsProperties.put(
"spring.groovy.template.cache"
,
"false"
);
devToolsProperties.put(
"spring.mustache.cache"
,
"false"
);
devToolsProperties.put(
"server.servlet.session.persistent"
,
"true"
);
devToolsProperties.put(
"spring.h2.console.enabled"
,
"true"
);
devToolsProperties.put(
"spring.resources.cache.period"
,
"0"
);
devToolsProperties.put(
"spring.resources.chain.cache"
,
"false"
);
devToolsProperties.put(
"spring.template.provider.cache"
,
"false"
);
devToolsProperties.put(
"spring.mvc.log-resolved-exception"
,
"true"
);
devToolsProperties.put(
"server.servlet.jsp.init-parameters.development"
,
"true"
);
devToolsProperties.put(
"spring.reactor.stacktrace-mode.enabled"
,
"true"
);
PROPERTIES = Collections.unmodifiableMap(devToolsProperties);
}
@Override
public
void
postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
if
(isLocalApplication(environment) && canAddProperties(environment)) {
PropertySource<?> propertySource =
new
MapPropertySource(
"refresh"
,
PROPERTIES);
environment.getPropertySources().addLast(propertySource);
}
}
private
boolean isLocalApplication(ConfigurableEnvironment environment) {
return
environment.getPropertySources().
get
(
"remoteUrl"
) ==
null
;
}
private
boolean canAddProperties(Environment environment) {
return
isRestarterInitialized() || isRemoteRestartEnabled(environment);
}
private
boolean isRestarterInitialized() {
try
{
Restarter restarter = Restarter.getInstance();
return
(restarter !=
null
&& restarter.getInitialUrls() !=
null
);
}
catch
(Exception ex) {
return
false
;
}
}
private
boolean isRemoteRestartEnabled(Environment environment) {
return
environment.containsProperty(
"spring.devtools.remote.secret"
);
}
}
|
4)devtools會在windows資源管理器佔用java進程,在開發工具裏面殺不掉,只能手動kill掉,不然重啓會選成端口重複綁定報錯。
Spring Boot如何定義多套不同環境配置?
簡單來說,Profile就是Spring Boot可以對不同環境或者指令來讀取不同的配置文件。
假如有開發、測試、生產三個不同的環境,需要定義三個不同環境下的配置。
1)基於properties文件類型可以另外建立3個環境下的配置文件:
1
2
3
4
|
applcation.properties
application-dev.properties
application-test.properties
application-prod.properties
|
然後在applcation.properties
文件中指定當前的環境spring.profiles.active=test
,這時候讀取的就是application-test.properties
文件。
2)基於yml文件類型,只需要一個applcation.yml文件即可,推薦此方式。關注微信公衆號“Java精選”(w_z90110),回覆關鍵字領取資料:如Mysql
,Hadoop
,Dubbo
,CAS
源碼等等,免費領取視頻教程、資料文檔和項目源碼。Java面試題持續更新中...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
spring:
profiles:
active: prod
---
spring:
profiles: dev
server:
port: 8080
---
spring:
profiles: test
server:
port: 8081
---
spring.profiles: prod
spring.profiles.include:
- proddb
- prodmq
server:
port: 8082
---
spring:
profiles: proddb
db:
name: mysql
---
spring:
profiles: prodmq
mq:
address: localhost
|
其中dev代表開發,test代表測試,prod代表正式環境。此時讀取的就是prod的配置,prod包含proddb,prodmq,此時可以讀取proddb,prodmq下的配置。也可以同時激活三個配置,如下:
1
|
spring.profiles.active: prod,proddb,prodmq
|
3)基於Java代碼,在JAVA配置代碼中也可以加不同Profile下定義不同的配置文件,@Profile
註解只能組合使用@Configuration
和@Component
註解。
1
2
3
4
5
|
@Configuration
@Profile(
"prod"
)
public
class
ProductionConfiguration {
// ...
}
|
4)指定Profile
main方法啓動方式:在Eclipse Arguments
裏面添加
1
|
--spring.profiles.active=prod
|
插件啓動方式:
1
|
spring-boot:run -Drun.profiles=prod
|
jar運行方式:
1
|
java -jar xx.jar --spring.profiles.active=prod
|
除了在配置文件和命令行中指定Profile,還可以在啓動類中寫死指定,通過SpringApplication.setAdditionalProfiles
方法
1
2
3
4
|
SpringApplication.
class
public
void
setAdditionalProfiles(String... profiles) {
this
.additionalProfiles =
new
LinkedHashSet<String>(Arrays.asList(profiles));
}
|
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)引入模板組件
1
2
3
4
|
<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容器可以:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
@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配置,可以:
1
2
3
|
@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節點:
1
2
3
4
5
|
<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元素的依賴管理來處理:
1
2
3
4
5
6
7
8
9
10
11
|
<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
無效:
1
2
3
|
// other annotations
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.
class
)
public
class
MyConfiguration { }
|
2)使用@SpringBootApplication
註解,將@EnableAutoConfiguration
作爲元註解的項來啓用自動化配置,使用相同名字的屬性來禁用自動化配置:
1
2
3
|
// other annotations
@SpringBootApplication(exclude = DataSourceAutoConfiguration.
class
)
public
class
MyConfiguration { }
|
3)使用spring.autoconfigure.exclude環境屬性來禁用自動化配置。
application.properties中的這項配置內容增加如下:
1
|
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屬性:
1
2
3
4
|
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
|
有了這個插件,可以在執行package步驟後得到一個JAR包。這個JAR包包含所需的所有依賴以及一個嵌入的服務器。因此,無需擔心去配置一個額外的服務器了。可以通過運行一個普通的JAR包來啓動應用程序。
需要注意的是,爲了打包成JAR文件,pom.xml
中的packgaing
屬性必須定義爲jar:
1
|
<packaging>jar</packaging>
|
如果不定義這個元素默認值也是jar。
如果想構建一個WAR文件,將packaging
元素修改爲war:
1
|
<packaging>war</packaging>
|
並且需要將容器依賴從打包文件中移除:
1
2
3
4
5
|
<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文件當中:
1
2
3
4
|
<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()啓動類中,用於加載:
1
2
3
4
5
6
7
8
9
10
11
12
|
@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():
1
2
3
4
5
6
7
8
9
10
|
@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
工具組件採用註解進行加載:
1
2
3
|
@WebFilter(filterName =
"customFilter"
, urlPatterns =
"/*"
)
@WebListener
@WebServlet(name =
"customServlet"
, urlPatterns =
"/custom"
)
|
Spring Boot中的application.properties配置文件是什麼,有哪些配置?
application.properties
爲Spring Boot
項目中的一個系統自帶的全局屬性配置文件,提供默認屬性重寫的作用。可包含重寫系統tomcat
,spring
,springmvc
,mybatis
等諸多默認配置屬性。列舉部分如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#全局配置文件: 重寫視圖解析器的資源地址
#頁面默認前綴目錄
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
文件增加內容如下:
1
|
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)提供非功能性特性例如安全和健康檢查給到生產環境中的應用程序。