Springboot 笔记(持续更新中)

10 篇文章 0 订阅
7 篇文章 0 订阅

一、控制任意返回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 就是生成的最终文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值