javascript
Spring Boot----基础
1、簡介
spring boot優點
快速創建獨立運行的Spring項目以及與主流框架集成
使用嵌入式的Servlet容器,應用無需打成WAR包
starters自動依賴與版本控制,(如果我們想用web工能,只需要導入web的started,如果MyBatis,只需要MyBatis的starts,里面自動幫我們配置了所有的依賴)
大量的自動配置,簡化開發,也可修改默認值無需配置XML
無代碼生成,開箱即用
準生產環境的運行時應用監控
與云計算的天然集成
?
由于提出了微服務的概念,如果按照傳統的模式開發,各個模塊xml配置導入jar包,服務器環境配置等等耗費時間人力,所以spring boot為分布式應用構建起到了很好的作用。各個應用的互相調用,我們使用spring cloud,分布式之間的數據處理我們使用spring cloud? data flow。
?
?
?一個簡單項目(使用maven工程創建):
1、導入包
<!--父項目:管理spring應用里所有依賴的版本,以后導入依賴包就不需要寫版本號(如果父項目沒有管理的包,自己還是需要些版本號的)--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.7.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!--spring-boot-starter:場景啟動器,幫我們導入web模塊正常運行所依賴的所有組件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><!--將項目打包一個可以執行的jar包(里面包含了tomcat服務器(嵌入式,所以spring boot不支持jsp))--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>?
2、添加spring boot主程序
/*主程序類*/ @SpringBootApplication public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);} }詳解
@SpringBootConfiguration:Spring Boot的配置類;
標注在某個類上,表示這是一個Spring Boot的配置類;
@Configuration:配置類上來標注這個注解;配置類==配置文件;配置類也是容器中的一個組件;@Component
@EnableAutoConfiguration:開啟自動配置功能;
以前我們需要配置的東西,Spring Boot幫我們自動配置;@EnableAutoConfiguration告訴SpringBoot開啟自動配置功能;這樣自動配置才能生效;
@AutoConfigurationPackage:自動配置包,將主配置類(@SpringBootApplication標注的類)的所在包及下面所有子包里面的所有組件掃描到Spring容器;(如果Controller比主程序(application)高一個目錄,默認情況Controller是掃描不到的)
@lmport(AutoConfigurationPackages.Registrar.class):Spring的底層注解@lmport,給容器中導入一個組件;由AutoConfigurationPackages.Registrar.class來指定導入那些組件
@Import(AutoConfigurationImportSelector.class)
? ?AutoConfigurationlmportSelector:導入哪些組件的選擇器;通過(public String[] selectImports(AnnotationMetadata annotationMetadata))這個方法,將所有需要導入的組件以全類名的方式返回;這些組件就會被添加到容器中;
@Import?會給容器中導入非常多的自動配置類(xxxAutoConfiguration);就是給容器中導入這個場景需要的所有組件,并配置好這些組件;有了自動配置類,免去了我們手動編寫配置注入功能組件等的工作;
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader());Spring Boot在啟動的時候從類路徑下的META-INF/spring.factories中獲取EnableAutoConfiguration指定的值,將這些值作為自動配置類導入到容器中,自動配置類就生效,幫我們進行自動配置工
作;以前我們需要自己配置的東西,自動配置類都幫我們配置;
J2EE的整體整合解決方案和自動配置都在C:\Users\zhengyan\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.7.RELEASE\spring-boot-autoconfigure-2.1.7.RELEASE.jar!\org\springframework\boot\autoconfigure
?
3、添加Controller
@RestController public class LoginController {@RequestMapping(value = "login")public String login2(){return "login"; //返回是一個字符串,原因是@RestController集成了@ResponseBody} }
?將spring boot打包成jar包:
1、首先maven里面依賴一個插件
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>2、雙擊 package
?
?使用?Spring Initializr 創建Spring Boot工程:
?
可以選擇其他的模塊,我們這只選擇web
?
IDEA會聯網,從Spring Boot官方網站生成出這個項目 (http://start.spring.io/starter.zip)
?
?目錄結構
resources文件夾中目錄結構
static:保存所有的靜態資源;js css images;
templates:保存所有的模板頁面;(Spring Boot默認jar包使用嵌入式的Tomcat,默認不支持JSP頁面);可以使用模板引擎(freemarker、thymeleaf);
application.properties:Spring Boot應用的全局配置文件(名字固定),可以自己配置來覆蓋Spring Boot默認的配置。
?
?java配置文件的配置和讀取 :
spring boot 所有的配置:https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/html/common-application-properties.html
在 src\main\resources下application.properties,配置
server.port=9090 server.context-path=/boot //項目訪問文件位置可以將application.properties修改為application.yml,配置(yml和yaml后綴都可以)
YAML:以數據為中心,比json和xml更適合做配置文件
server:port: 9090servlet:context-path: /boot #設置虛擬目錄 # path: "*.html" #沒有成功?
YAML和properites的優先級
加載順序是? yml > yaml > properties,后加載的會覆蓋先加載的,一定的
對于優先級,可能是這樣描述的,后加載的文件優先級高(不確定)
?
YAML語法
1、基本語法
k: v? :表示一個鍵值對(注意 ":"和"v"之間需要有一個空格)
屬性和值大小寫敏感
2、值的寫法
值是 普通字符串
k: v? ?:v就按照字面值來寫,字符串默認不加單引號或者雙引號
? ? ? ? ?“v” 雙引號,提供轉義序列
name: "zy \n" //會輸出zy 換行,就是雙引號不會去轉義特殊字符,\n 輸出就變成了換行了? ‘v’ 單引號,?當不需要轉義時,單引號樣式很有用。
name: 'zy \n' 會輸出 zy \n,就是單引號會將 \n轉義成 \\n,\\n 輸出就成了 \n 普通字符了值是 對象/Map
k: v? ?:對象還是k: v的形式
user:name: zyage: 18行內寫法
user: {name: zy,age: 18}值是 數組(List,set)
用? - 值 表示數組中的一個元素
animal:- dog- cat- pig行類寫法
animal: [dog,cat,pig]
@ConfigurationProperties讀取配置文件和java對象綁定
導入配置文件處理器(目的:在寫yml或者properties的時候會出現提示,如果不配置也可以)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional> </dependency>?
User
/*** 將配置文件中的每一個屬性映射到這個對象中* 使用 @ConfigurationProperties注解將yml中的配置和該對象進行綁定* prefix: 指定yml配置中的key,該key下的配置會和該對象進行綁定* @Component:使用注解將User裝配到spring 容器中**/ @Component @ConfigurationProperties(prefix = "user") public class User {private String username;private Date date;private Dog dog;private Map<Integer,String> map;private List<String> list;//省略get、set方法 )Dog
public class Dog {private String name; }application.yml
user:username: zydate: 2019/01/01dog:name: wangzimap: {1: v1,2: v2}list:- a- b- c如果使用 application.properties,參考下面配置
user.username=zy user.date=2019/01/01 #注意如果user.list=[a,b],那么[a,b,c]就是一個整體了 user.list=a,b,c user.map.1=v1 user.dog.name=旺仔Spring Boot 單元測試
@RunWith(SpringRunner.class)@SpringBootTest public class SpringbootProjectApplicationTests {@Autowiredprivate User user;@Testpublic void contextLoads() {System.out.println(user);} }
?
如果使用application.properties出現亂碼(配置下面的,如果還是出現亂碼,將application.properties文件刪除重新創建)
?
@Value讀取配置文件和java對象綁定
讀取yml的方式和properties方式一樣,通過 "."
@Component @Data public class User {@Value("${user.username}") //使用配置文件的private String username;@Value("2019/01/01") //自定義valueprivate Date date;@Value("#{1+1}") //spring 表達式?
@ConfigurationProperties和@Value的區別
松散綁定指的是
實體類: private String userName;yml: user:userName: zy //屬性可以被注入 或者 user:user-name: zy //屬性也可以被注入(@Value("user-name")不等于@Value("userName"))JSR303數據校驗
對于@configurationProperties,數據的注入會驗證
@Component @Data @ConfigurationProperties(prefix = "user") @Validated //需要添加 public class User {@Emailprivate String userName; }對于@value,不支持,數據不會被驗證
@Component @Data @Validated public class User {@Email@Value("${user.username}")private String userName; }復雜類型封裝
@value不能取出配置中的Map,List等復雜數據,會報錯
@Value("${user.map}") private Map<Integer,String> map;
@PropertySource
可以讀取指定的配置文件(不是全局的,不能以yml做后綴),但是注意會被全局配置文件application.yml和application.properties覆蓋掉。
@ConfigurationProperties(prefix = "user") @PropertySource(value = "classpath:test.properties") @Component @Data public class User {//@Value("${user.username}")private String userName;?
給spring 容器添加組件
1、@ImportResource
?可以用它來導入spring配置文件(利用xml配置給spring 容器添加組件),讓其生效(spring boot不推薦使用)
@ImportResource(value = {"classpath:spring-context.xml"}) @SpringBootApplication public class SpringbootProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootProjectApplication.class, args);} }2、使用配置類
/*@configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件*/ @Configuration public class MyAppConfig {/*將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名*/@Beanpublic LocalValidatorFactoryBean validator(){LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();return localValidatorFactoryBean;} }替換xml來裝配 Bean
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> </beans>
配置文件占位符
占位符獲取之前配置的值,如果沒有可以是用:指定默認值
user.age=${random.int} //可以寫一個隨機數 user.name=${persion.test} //如果persion.test不存在,那么user.name="${persion.test}" user.name=${perison.test:test} //如果persion.test不存在,那么user.name="test"
Profile
1、編寫多個Profile文件,文件名格式:application-(profile}.properties/yml,例如
application-dev.properties //指定開發環境中使用該配置 application-prod.properties //指定生產環境中使用該配置1.2、激活該配置(在application.properties/yml 插入spring.profiles.active=dev)
spring.profiles.active=dev //以這個配置中端口號為主(dev中的配置會覆蓋全局配置,就是全局配置優先加載) server.port=80811.2、如果使用yml,我們還可以使用yml的文檔塊來指定激活那個配置(使用"---"來分割不同的配置文件,此時分割的不同文檔就相當于一個application-dev/prod.yml,下面IDEA配置也可以識別到這個配置)
server:port: 8081 spring:profiles:active: prod //指定激活下面的那個配置 --- server:port: 8082 spring:profiles: prod --- server:port: 8083 spring:profiles: dev1.2、啟動項目指定參數,在項目配置中(--spring.profiles.active=dev)
?
1.2 當將這個項目打包成jar包的時候,可以使用命令的形式java -jar spring.xxx.jar --spring.profiles.active=dev 運行jar包(指定了配置文件),【這個和上面的IEDA方式是一樣的,啟動的時候指定參數】
?
?1,2 通過虛擬機參數,在項目配置中(-Dspring.profiles.active=dev)
?
spring.config.location
如果我們項目已經打包好了,我們有添加了一些配置,我們可以通過這個命令,讓項目指定加載本地磁盤的配置文件。
java -jar spring.xx.jar spring.config.location=G:/application.properties //如果這個文件不和項目同級(同級的話參考spring外部文件配置)
spring boot內部配置文件位置以及加載順序
優先級高(會覆蓋下面的配置,真實)-file:/config/ //在當前項目下創建config目錄,在目錄下創建application.yml(這個文件是不打包的) -file./ //在當前項目下創建application.yml(注意這個文件也是不打包的) -classpath:/config/ //在resources目錄下創建config目錄,將配置文件放進去 -classpath:/ //resources目錄
低
注意,可能優先級高,不代表優先啟動,優先級高,可能是說明配置優先
?
spring boot 內部加外部配置文件加載順序
1、使用命令行修改配置參數,例如,多個配置用空格分開(優先級最高)
java -jar spring.xx.jar --server.port=80872. SPRING APPLICATION JSON中的屬性。 SPRING_APPLICATION—JSON是以JSON格式配置在系統環境變量中的內容。
3. java:comp/env中的JNDI 屬性。
4. Java的系統屬性, 可以通過System.getProperties()獲得的內容。
5 操作系統的環境變量 。
6 通過random.*配置的隨機屬性。
7、jar包外部的application-(profile}.properties或application.yml(帶spring.profile)配置文件
8、jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
9、jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
10、jar包內部的application.properties或application.yml(不帶spring.profile)配置文件
在jar包外部寫一個application.properties,也同樣會被識別(帶profile的配置需要在全局配置中定義)11、@Configuration注解類上的@PropertySource
12、通過SpringApplication.setDefaultProperties指定的默認屬性
?
?
?
?
?單元測試:
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner;import java.net.URL;import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat;@RunWith(SpringRunner.class) @SpringBootTest(classes = DemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //為了裝載application.yml 配置的 public class HelloSpringBootApplicationTests {@LocalServerPortprivate int port;private URL base;@Autowiredprivate TestRestTemplate template;@Beforepublic void setUp() throws Exception {this.base = new URL("http://localhost:" + port + "/");}@Testpublic void contextLoads() {ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);assertThat(response.getBody(), equalTo("hellow")); //斷言返回值是不是hellow}}
?
?
?自定義 Banner:
我們在?src/main/resources?目錄下新建一個 banner.txt
通過?http://patorjk.com/software/taag?網站生成字符串,將網站生成的字符復制到 banner.txt 中,再次運行這個程序(可以直接將下面的圖案復制到banner.txt文件中)
${AnsiColor.BRIGHT_RED}// _ooOoo_ // // o8888888o // // 88" . "88 // // (| ^_^ |) // // O\ = /O // // ____/`---'\____ // // .' \\| |// `. // // / \\||| : |||// \ // // / _||||| -:- |||||- \ // // | | \\\ - /// | | // // | \_| ''\---/'' | | // // \ .-\__ `-` ___/-. / // // ___`. .' /--.--\ `. . ___ // // ."" '< `.___\_<|>_/___.' >'"". // // | | : `- \`.;`\ _ /`;.`/ - ` : | | // // \ \ `-. \_ __\ /__ _/ .-` / / // // ========`-.____`-.___\_____/___.-`____.-'======== // // `=---=' // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // 佛祖保佑 永不宕機 永無BUG //
?日志配置:
Spring Boot 對各種日志框架都做了支持,我們可以通過配置來修改默認的日志的配置 默認情況下,Spring Boot 使用 Logback 作為日志框架
application.yml添加配置
logging:file: ../logs/spring-boot-hello.loglevel.org.springframework.web: DEBUG
?關閉特定的自動配置:
如果我們不需要自動配置
關閉特定的自動配置使用?@SpringBootApplication?注解的?exclude?參數即可,這里以關閉數據源的自動配置為例
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
?
?
?springBoot一些配置的修改:
spring.mvc.date-format=yyyy/MM/dd HH:mm:ss //默認格式化時間的修改
?
轉載于:https://www.cnblogs.com/yanxiaoge/p/10803850.html
總結
以上是生活随笔為你收集整理的Spring Boot----基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何调用Altera FPGA的内嵌乘法
- 下一篇: Day 6 上午