1. 程式人生 > >Springboot 筆記(持續更新中)

Springboot 筆記(持續更新中)

一、控制任意返回JSON與XML型別

        1、pom檔案匯入依賴

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-xml-provider</artifactId>
    <version>2.5.0</version>
</dependency>
        2、Controller中@RequestMapping 註解中新增 produces = {"application/json" , "application/xml"}
@RequestMapping
(value = "dic/getDicAll", produces = {"application/json", "application/xml"}) @ResponseBody public List<DicModel> getDicAll() { return ds.findAll(); }

        3、http://localhost:8080/dic/getDicAll.json 返回json資料,getDicAll.xml 返回xml資料。

二、thymeleaf 設定不校驗html標籤

預設配置下,thymeleaf對.html的內容要求很嚴格,比如,如果少封閉符號/,就會報錯而轉到錯誤頁。也比如你在使用Vue.js這樣的庫,然後有<div v-cloak></div>這樣的html程式碼,也會被thymeleaf認為不符合要求而丟擲錯誤。

通過設定thymeleaf模板可以解決這個問題,下面是具體的配置:

spring.thymeleaf.cache=false

spring.thymeleaf.mode=LEGACYHTML5

LEGACYHTML5需要搭配一個額外的庫NekoHTML才可用 專案中使用的構建工具是Maven新增如下的依賴即可完成:

<dependency>

<groupId>net.sourceforge.nekohtml</groupId>

<artifactId>nekohtml</artifactId>

<version>1.9.22</version>

</dependency>

三、Springboot通過設定devtools實現熱部署

        1、pom檔案引入依賴

<!--熱部署-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <version>1.5.7.RELEASE</version>
    <optional>true</optional>
</dependency>
<!--熱部署-->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
<!--支援靜態檔案熱部署-->
<addResources>true</addResources>
    </configuration>
</plugin>
  2、Intellij IEDA開發工具,還需要到設定裡將project automatically勾選上;File->Setting->Build,…->Compiler  將右側project automatically勾上       3、     Intellij IEDA 使用ctrl+shift+a 快捷鍵搜尋Registry,選擇搜尋出來的第一個。       4、     找到compiler.automake.allow.when.app.running,勾上開啟此功能即可。此時重新啟動專案即可實現熱部署,改動任意程式碼會立即生效,不用再每次重新啟動專案

四、Springboot讀取資原始檔

場景:讀取靜態資原始檔 countries.xml 放在 src/main/resources 目錄下

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

五、Springboot properties檔案轉bean

@Component
@PropertySource(value = "classpath:application-test.properties")
@ConfigurationProperties(prefix = "com.lhzs.springdemo")
public class TestProperties {

    private String basePath;
    public String getBasePath() {
        return basePath;
}

    public void setBasePath(String basePath) {
        this.basePath = basePath;
}
}

Idea出現spring boot Configuration Annotation Proessor not found in classpath的提示是在用了@ConfigurationProperties這個註解時,所以問題出現在ConfigurationProperties註解。

解決方案:新增下面依賴

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

六、spring boot @ConditionalOnxxx相關注解總結

@ConditionalOnBean(僅僅在當前上下文中存在某個物件時,才會例項化一個Bean)
@ConditionalOnClass(某個class位於類路徑上,才會例項化一個Bean)
@ConditionalOnExpression(當表示式為true的時候,才會例項化一個Bean)
@ConditionalOnMissingBean(僅僅在當前上下文中不存在某個物件時,才會例項化一個Bean)
@ConditionalOnMissingClass(某個class類路徑上不存在的時候,才會例項化一個Bean)
@ConditionalOnNotWebApplication(不是web應用)

另一種總結

@ConditionalOnClass:該註解的引數對應的類必須存在,否則不解析該註解修飾的配置類;
@ConditionalOnMissingBean:該註解表示,如果存在它修飾的類的bean,則不需要再建立這個bean;可以給該註解傳入引數例如@ConditionOnMissingBean(name = "example"),這個表示如果name為“example”的bean存在,這該註解修飾的程式碼塊不執行。

七、spring boot 按條件事務回滾

1、
@Transactional(rollbackFor = Exception.class)
public List<VQgpzStoreModel> findByPage(Long id) {
     
    throw new RuntimeException("測試");
    return dao.findByPage(qs);
}

2、EntityManager em;
EntityTransaction transaction = em.getTransaction();
    transaction.begin();
 if(id<0){
transaction.rollback();
}

transaction.commit();

八、Jackson 解析不規範JSON資料

@JsonProperty(value = "ActionStatus")
private String actionStatus;
@JsonProperty(value = "ErrorInfo")
private String errorInfo;
@JsonProperty(value = "ErrorCode")
private int errorCode;
@JsonProperty(value = "QueryResult")
private List<QueryResultBean> queryResult;

九、自動生成RestDoc文件與單元測試Junit

1、引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.restdocs</groupId>
    <artifactId>spring-restdocs-mockmvc</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test-autoconfigure</artifactId>
</dependency>

2、引入asciidoc編譯外掛

<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>generate-docs</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <sourceDocumentName>index.adoc</sourceDocumentName>
                <backend>html5</backend>
                <doctype>book</doctype>
                <attributes>
                    <snippets>${project.build.directory}/snippets</snippets>
                </attributes>
            </configuration>
        </execution>
    </executions>
</plugin>

3、安裝asciidoc編輯外掛

搜尋安裝 AsciiDoc

4、編寫測試用例

public static final String ASCII_DOC_HOME_PATH = "target/snippets";//doc生成地址
@RunWith(SpringRunner.class)
@SpringBootTest
public class IndexControllerTest extends BaseTest {

    @Autowired
private WebApplicationContext context;
    private MockMvc mvc;
@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(Constant.ASCII_DOC_HOME_PATH);
@Before
public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(context)
                .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)
                        .uris().withScheme("http").withHost("localhost").withPort(8080)).build();
}


    @Test
public void testLogin() {
        try {
            request("/getOne", HttpMethod.GET, "login");
} catch (Exception e) {
            e.printStackTrace();
}
    }

    @Override
public MockMvc mockMvc() {
        return mvc;
}
}
package com.example.demo.test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public abstract class BaseTest {

    public abstract MockMvc mockMvc();
    void request(String url, HttpMethod method, String docDirName) throws Exception {
        MockHttpServletRequestBuilder request = null;
        switch (method) {
            case GET:
                request = MockMvcRequestBuilders.get(url);
                break;
            case POST:
                request = post(url);
                break;
}
        if (request != null) {
            mockMvc().perform(request)
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andDo(document(docDirName))
                    .andReturn()
                    .getResponse()
                    .getContentAsString();
}
    }

    void requestBody(String url, String body, String docDirName) throws Exception {
        MockHttpServletRequestBuilder request = post(url);
mockMvc().perform(request
                .contentType(MediaType.APPLICATION_JSON)
                .content(body)).andDo(print())
                .andExpect(status().isOk())
                .andDo(document(docDirName))
                .andReturn()
                .getResponse()
                .getContentAsString();
}
}

5、執行測試用例生成 .adoc檔案


6、src/main/asciidoc路徑下建立index.adoc

= API文件
*1、登陸、返回使用者資訊*

.介面地址/引數
include::{snippets}/login/http-request.adoc[]
[options="header"]
|===
| 引數名  |  型別    | 說明
| name   |  String  |  使用者名稱
|===

.返回
include::{snippets}/login/http-response.adoc[]
|===
| 引數dd|  dd    | dd
| name   |  String  |  使用者名稱
|===

====
WARNING: 1.Wolpertingers are known to nest in server racks.
====


*2、測試介面*

.介面地址/引數
include::{snippets}/sayHello/http-request.adoc[]

.返回
include::{snippets}/sayHello/http-response.adoc[]

文件編寫格式參考:點選開啟連結

7、執行manen   pagage 命令打包 生成文件,文件路徑:target/generated-docs  路徑下index.html 就是生成的最終文件