1. 程式人生 > 其它 >springboot 單測加入引數_SpringBoot基礎筆記

springboot 單測加入引數_SpringBoot基礎筆記

技術標籤:springboot 單測加入引數

1、IDEA無法下載jar包、無法聯網

​ 解決:pom.xml檔案里加入阿里雲搭建的國內映象http://maven.aliyun.com,跑起來速度很快,可以進行配置 ​

<repositories>
        <repository>
            <id>nexus-aliyun</id>
            <name>nexus-aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
</repositories>

2、SpringBoot 404啟動失敗

  • 檔案對映路徑不對
  • 註解沒加 @RequestMapping("/路徑") 或 @Responsebody
  • 檔案必須處在啟動類所在包的子包下

3、想同時存在兩個專案,IDEA預設一個視窗一個專案

​ 解決:在已有專案的前提下,如果還想新增其他專案

​ 通過New->Module新建

4、IDEA資料夾包名不能斷開

小齒輪設定->Flatten Packages,即可。

5、SpringBoot配置檔案

application.properyies:

server.port = 8080   更改Tomcat埠

application.yml

server:
    port: 8080

若設定衝突,優先順序為:properyies > yml

6、SpringBoot引導註釋處理器未配置

使用註解@ConfigurationProperties(prefix = “girl”)之後報錯

解決辦法:POM檔案加入依賴

<dependency>
   <groupId> org.springframework.boot </groupId>
   <artifactId> spring-boot-configuration-processor </artifactId>
   <optional> true </optional>
</dependency>

7、靜態資源

預設靜態資源載入路徑:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

注意:這是SpringBoot2.0之前,2.0之後有所變動,暫時未知如何配置

預設歡迎頁:index.html

預設網頁logo:favicon.ico

在任意靜態路徑中使用即可,但名稱要一樣。

自定義靜態資源:配置檔案中宣告:spring.resources.static-locations = classpath:/static

如果有多個,用逗號分割

設定服務專案名server.servlet.context-path = /demo

8、@ConfigurationProperties和@Value的區別

| spring| @ConfigurationProperties | @Value | 例項 | | -------------- | ------------------------ | ---------- | ------------------ | | 實現功能 | 批量注入值 | 單一注入值 | | | 鬆散語法 | 支援 | 不支援 | last-name=lastName | | SpEL | 不支援 | 支援 | #{10*2} | | 複雜型別封裝 | 支援 | 不支援 | emp.map | | JSR303資料校驗 | 支援 | 不支援 | |

二者優先順序:@ConfigurationProperties > @Value

@Value獲取配置檔案的值:例如:@Value("${emp.age}")

9、資料校驗(@Value不支援)

實體類加註解@Validated(開啟JSR303資料校驗)

屬性加校驗條件:例如驗證郵箱:@Email

10、載入區域性配置檔案(出現問題,暫未解決!!!)

類路徑下新建配置檔案,例如:emp.properties

設定好對應屬性的值

實體類加註解:@PropertySource(value = {"classpath:emp.properties"}, encoding = "utf-8")

11、匯入xml配置檔案

有些時候,我們不得不使用xml配置檔案,使用方法:

  1. 類路徑下新建xml配置檔案springConf.xml,右鍵New-> XML Configuration File -> Spring Config ,進行自己想要的配置
  2. 啟動類加註解:@ImportResource(Locations={"classpath:springConf.xml"})
@Autowired
    ApplicationContext context;

    @Test
    public void testConf(){
        EmpService empservice = (EmpService) context.getBean("empService");
        empservice.test();
        System.out.println();
    }

12、配置類替換xml配置檔案(推薦)

SpringBoot官方推薦使用配置類形式注入,使用方法

新建配置類,類加註解@Configuration,方法加註解@Bean,如下:

@Configuration
public class EmpConfig {

    @Bean
    public EmpService empservice2(){
        return new EmpService(); // 配置類裡方法的返回值必須是要注入的元件物件
    }
}

要注入的Service方法:

public class EmpService {

    public void testClass(){
        System.out.println("注入service元件成功!!!!");

    }
}

測試配置類注入:

@Test
    public  void testConfigClass(){
        EmpService empservice = (EmpService) context.getBean("empservice2");
       // getBean裡的id值是配置類裡的方法名
        empservice.testClass();
    }

13、Profile的多環境切換

Profile是Spring用來針對不同的環境要求,提供不同的配置支援

application.properties多環境切換

命名規則:application-環境名.properties

例如:

  • application.properties(預設環境)
  • application-dev.properties(測試環境)
  • application-prod.properties(生產環境)

如何確定使用哪個properties環境?

application.properties(預設環境)中宣告:

spring.profiles.active=dev   # 宣告使用dev環境

application.yml多環境切換

server:
  port: 8080    # 預設環境
spring:
  profiles:
    active: dev  # 顯式宣告使用dev環境,埠號為:6464
---  # 使用三個“-”來分割環境  
server:
  port: 6464
spring:
  profiles: dev   # 測試環境

---
server:
  port: 5252
spring:
  profiles: prod  #開發環境

執行引數切換環境

上方下拉三角框 -> Edit Configurations -> Environment -> Program arguments ,寫入

--spring.profiles.active=prod  # 切換prod環境

注意:這種方式優先順序要大於properties和yml配置檔案

虛擬機器引數切換環境

同樣上面的路徑,只不過在VM options輸入框中填入

-Dspring.properties.active=dev

優先順序:VM options < Program arguments

打成JAR包情況下切換環境

  1. 利用Maven將程式打包
  2. cmd命令列進入包的資料夾執行命令
java -jar jar包全名 --spring.profiles.active=prod  # 使用prod環境

優先順序:此類方法優先順序最高。

14、配置檔案載入位置

  • SpringBoot啟動時,會掃描以下位置的application.propertiesapplication.yml

| 配置檔案位置 | 說明 | | -------------------- | ---------------------------------- | | root目錄/config/ | 根目錄下的config目錄下(級別最高) | | root目錄 | 跟目錄 | | classpath:/config/ | 類路徑的config目錄下 | | classpath: | 類路徑下(級別最低) |

  • 配置檔案載入順序:由下往上逐層覆蓋,這樣一來root目錄/config/級別就是最高的。
  • 注意:==如果使用IDEA建立的專案是 Module (如果是 Project 則忽略),當前專案的根目錄不是你這個專案所有目錄(是Project所在目錄) ,這樣使用 file: 存放配置檔案時會找不到配置==

配置檔案常用屬性:SpringBoot官網連結

15、SpringBoot日誌配置

  • Spring Boot 採用了 slf4j+logback的組合形式,Spring Boot也提供對JULlog4j2Logback提供了預設配置
  • 由於預設配置好了,只要啟動 Spring Boot 專案就會在控制檯輸出日誌資訊。

設定日誌等級

==日誌等級劃分:trace < debug < info < warn < error==

#設定某個包的級別
logging.level.包名=trace
#設定root級別(SpringBoot自帶包的級別)
logging.level.root=debug

輸出日誌到檔案

  • application.properties配置檔案中修改配置檔案
# 輸出到當前專案根目錄下的springboot.log檔案中
logging.file = springboot.log

# 輸出到E盤下的springboot.log檔案中
logging.file = E:/springboot.log

# 輸出到當前專案所在磁碟根目錄下的springboot資料夾中的springboot.log
logging.path = /springboot/springboot.log
  • 推薦使用logging.file來定義日誌輸出檔案,它可以自由定義日誌輸出位置以及檔名稱。
  • 都是以追加方式輸出到檔案

修改日誌輸出格式

  • application.properties配置檔案中修改配置檔案
# 修改控制檯輸出的日誌格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n

# 修改檔案中輸出的日誌格式
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} >>> [%thread] >>> %-5level >>> %logger{50} >>> %msg%n

16、Thymeleaf教程

Thymeleaf-獲取值輸入

  • 控制層程式碼

java @RequestMapping("/success") public String success(Map<String,Object> map){ map.put("name","張帥"); return "success"; }

  • 前臺,如果沒獲取到值,則顯示標籤中的文字。
<p th:text="${name}">這是應該被替換的文字</p>

Thymeleaf-公共宣告

  • html公共檔案設定
<!--thymeleaf方式的公共宣告-->
<p th:fragment="header_common">這是公共宣告部分</p>

<!--id方式的公共宣告-->
<p id="header_common_id">這是id公共宣告部分</p>
  • 使用方法
<div>
   <p th:replace="header :: header_common"></p>
</div>
<div>
   <p th:replace="header :: #header_common_id"></p>
</div>

Thymeleaf-迭代 th:each

<!--  這是迭代器的關鍵詞,和常見用途

user : 第1個值,代表每次迭代出物件,名字任意取
iterStat : 第2個值,代表每次迭代器內建物件, 名字任意取, 並有如下屬性:
     index : 當前迭代下標 0 開始
     count : 當前迭代下標 1 開始
     size : 獲取總記錄數
     current : 當前迭代出的物件
     even/odd : 當前迭代是偶數還是奇數 (1開始算,返回布林值)
     first : 當前是否為第一個元素  是則返回true,不是則false,下面同理。
     last : 當前是否為最後一個元素
!-->
  • 控制層
@RequestMapping("/testEach")
    public String testEach(Map<String,Object> map){
        List<User> userList = new ArrayList<>();
        userList.add(new User("小明",1));
        userList.add(new User("小紅",0));
        userList.add(new User("小強",1));
        map.put("userList",userList);
        return "study";
}
  • 前臺接收遍歷輸出
<table border="1px">   <!--使用表格承載資料並輸出-->
        <tr>
            <th>姓名</th>
            <th>年齡</th>
            <th>序號</th>
            <th>奇偶數</th>
            <th>首個元素</th>
            <th>末尾元素</th>
        </tr>
        <tr th:each="user,iterStat : ${userList}">  <!---->

            <td th:text="${user.name}"></td>
            <td th:text="${user.gender==1 ? '男':'女'}">未知</td>
            <td th:text="${iterStat.count}">未知</td>
            <td th:text="${iterStat.even==false ? '奇數':'偶數'}">未知</td>
            <td th:text="${iterStat.first}">未知</td>
            <td th:text="${iterStat.last}">未知</td>
        </tr>
    </table>

Thymeleaf條件判斷

  • th:if th:unless 和 th:swich th:case

控制層程式碼

@RequestMapping("/testEach")
    public String testEach(Map<String,Object> map){
        List<User> userList = new ArrayList<>();
        userList.add(new User("小明",1));
        userList.add(new User("小紅",0));
        userList.add(new User("小強",1));
        map.put("userList",userList);
        map.put("sex",1); //這裡性別是1,為女生
        return "study";

}

HTML檔案

<p th:if="not ${#lists.isEmpty(userList)}">如果你看到這些文字證明集合有值</p>
<!--th:unless可以看做是th:if的相反對立面-->
<p th:unless="${#lists.isEmpty(userList)}">如果你看到這些文字證明集合無值</p>
<hr />
<div th:switch="${sex}">
   <p th:case="1">女生</p>
   <p th:case="2">男生</p>
<!--如果不符合以上條件,則輸出下面的預設值-->
   <p th:case="*">未知</p>

</div>

Themeleaf文字輸出與物件屬性值獲取

文字輸出

<!--輸出文字測試-->
    <!--th:text會原樣輸出文字內容,不識別標籤-->
    <p th:text="${desc}"></p>

    <!--th:utext會識別標籤,轉化為對應的樣式-->
    <p th:utext="${desc}"></p>

物件獲取屬性值

控制層

@RequestMapping("/testEach")
    public String testEach(Map<String,Object> map, HttpServletRequest request) {
        List<User> userList = new ArrayList<>();
        userList.add(new User("小明",1));
        userList.add(new User("小紅",0));
        userList.add(new User("小強",1));
        map.put("userList",userList);
        map.put("sex",1); //這裡性別是1,為女生
        map.put("desc","<h1>我是測試文字<h1>");

        request.getSession().setAttribute("user", new User("小不點", 2));
        return "study";

    }

HTML檔案

<!--使用th:object 直接取出物件,然後寫物件裡的屬性名即可獲取屬性值-->
    <div th:object="${session.user}">
        <p>
            姓名:<span th:text="*{name}">xxxx</span>
        </p>
        <p>
            性別:<span th:text="*{gender == 1 ? '女':'男'}">xxxx</span>
        </p>
    </div>

通過webjars引入依賴

  • pom.xml新增jquery依賴
<dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.3.1</version>
 </dependency>
  • 前臺引入方式
<script th:src="@{webjars/jquery/3.3.1/jquery.js}"></script>

應用會自動去webjars下的目錄裡尋找對應的檔案。

17、SpringBoot熱部署設定

  • 在開發中,我們修改一個檔案後,要重啟應用。會浪費很多時間,我們希望在不重啟的情況下,程式可以自動熱部署,不需要重啟。

新增SpringBoot熱部署依賴

<!--熱部署-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

配置檔案禁用模板快取

#開發環境下關閉thymeleaf模板緩
spring.thymeleaf.cache=false

手動Ctrl+F9(其實IDEA有熱部署,但效果不明顯,所以還是手動按鍵進行Build)

  • 此時可以直接重新整理瀏覽器看到效果。

18、配置資源路徑對映類

  • 我希望自定義預設的訪問,也就是localhost:8080可以訪問到模板檔案main/login.htm
@Configuration
public class MySpringMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("main/login");
    }
   /* 另一種方法,不需要實現介面,利用匿名類方式返回WebMvcConfigurer物件
   @Bean   
    public WebMvcConfigurer webMvcConfigurer(){
        return  new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("main/login");
            }
        };
    }*/
}

19、語言國際化設定

  • resources目錄下建立i18n資料夾
  • 利用IDEA方式建立對應的國際化檔案。zh_CN:中文 en_US:英文(美國)

自定義區域解析器

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Locale;

/**
 * @author zhang
 * @date 2020/1/4 15:39
 * @description
 */
public class MyLocaleResolver implements LocaleResolver {
    /**
     * 自定義區域解析器
     * @param httpServletRequest
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language = httpServletRequest.getParameter("l");
        // 先將預設的請求引數賦值給locale,防止l為空。
        Locale locale = Locale.getDefault();
        // 如果locale不為空,則進行獲取自定義資訊
        if (!StringUtils.isEmpty(language)){
            String[] split = language.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

將區域解析器在配置類裡注入spring容器

@Bean
 public LocaleResolver localeResolver() {
      return new MyLocaleResolver();
}

前臺傳送連結

<div style="margin-left: 100px;">
   <a href="#" th:href="@{/index.html(l='zh_CN')}">中文</a>
   <a href="#" th:href="@{/index.html(l='en_US')}">English</a>
</div>