【Springboot】springboot使用记录[个人版]

【Springboot】springboot使用记录[个人版],第1张

目录
  • 创建项目
  • 启动类出错
  • 打包速度
  • 数据库配置
    • 链接失败密码问题
    • mybatis-plus
      • 表的匹配和id自增
      • 拦截器
  • 日志记录
  • 校验
  • 计量单位
  • 临时专用属性
  • 临时专用配置
  • 测试类
    • 随机端口
    • 发送虚拟请求
    • 事务回滚
  • 配置文件随机值
  • 数据层技术选型
  • Redis
  • MongoDB



创建项目

首先就是创建,创建SpringBoot工程方法很多。工具自动,人工手动。

工具经典方法:

选择JDK时,建议1.8

之后就是耐心等待,网好一次过,网卡请努力

web工程

mybatis,如使用mybatis-plus手动pom

选择好所需,下一步

创建完成,刷新maven即可使用。

或者使用阿里,速度更快,但配置和项目结构有些不同。

手动方式无非复制之前创建好的项目,修改名称,**注意pom中名称的修改,**然后刷新pom。

启动类出错

IDEA没有加载启动类?

打开启动类,等待spring管理

然后运行就好了

打包速度

关闭test

目前还是很慢,但有提升。

数据库配置 链接失败密码问题

测试多种组合

数字和特殊字符识别错误(进制和格式问题)

例子:

dataSource:
  password: 9.

测试类

@SpringBootTest
class Springboot13ConfigurationApplicationTests {

   @Value("${dataSource.password}")
   private String password;

   @Test
   void contextLoads() {
      System.out.println(password);
   }

}

使用""包裹密码,解决问题

mybatis-plus 表的匹配和id自增

拦截器

配置分页拦截器

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //配置mp拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //配置具体拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}
日志记录

红框必备

level:后添加mapper包即可

使用mybatis修改第一行,删除-plus

file-name-pattern使用全路径

校验

<dependency>
   <groupId>javax.validationgroupId>
   <artifactId>validation-apiartifactId>
dependency>

实体类

//2.开启校验
@Validated
public class ServletConfig {
    private String ipAddress;
    //3.设置校验规则
    @Max(value = 100,message = "最大值不该超过100")
    private int port;
    private long timeout;
}

<dependency>
   <groupId>org.hibernate.validatorgroupId>
   <artifactId>hibernate-validatorartifactId>
dependency>

设置最大值100的限制,实际101

servlet:
  ipAddress: 192.168.0.1
  port: 101
  timeout: -1

超过提示

计量单位

实体类

@ConfigurationProperties(prefix = "servlet")
@Component
@Data

public class ServletConfig {
    private String ipAddress;
    private int port;
    
    @DurationUnit(ChronoUnit.HOURS)
    private Duration timeout;
}
servlet:
  ipAddress: 192.168.0.1
  port: 50
  timeout: 10

启动类

ServletConfig bean = run.getBean(ServletConfig.class);
System.out.println(bean);

临时专用属性

测试时yml中无配置,如有配置注解优先

方法一:

@SpringBootTest(properties = {"test.prop = testValue1"})
public class PropertiesAndArgsTest {

    @Value("${test.prop}")
    private String prop;

    @Test
    void testProperties(){
        System.out.println(prop);
    }
}

方法二:

@SpringBootTest(args = {"--test.prop=testValue2"})
public class PropertiesAndArgsTest {

    @Value("${test.prop}")
    private String prop;

    @Test
    void testProperties(){
        System.out.println(prop);
    }
}

args优先级大于properties

临时专用配置

不使用配置类注解

// @Configuration
public class MsgConfig {

    @Bean
    public String msg(){
        return "textMsgConfig";
    }

}

使用Import注解可以加载临时配置

@SpringBootTest
@Import(MsgConfig.class)
public class TestMsgConfig {

    @Autowired
    private String msg;

    @Test
    void testMsg(){
        System.out.println(msg);
    }

}

测试类 随机端口
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestWeb {

    @Test
    void test(){

    }
}

发送虚拟请求

controller

@RestController
@RequestMapping("/books")
public class BookController {

    @GetMapping
    public String getById(){
        System.out.println("getById...");
        return "books";
    }

}

test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class TestWeb {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void test() throws Exception {
        //虚拟路径
        MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
        //执行
        mockMvc.perform(mockHttpServletRequestBuilder);
    }
}

设置预期值

状态预期

MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);

//设置预期值
//定义预期值 status模拟状态
StatusResultMatchers status = MockMvcResultMatchers.status();
//预计状态
ResultMatcher ok = status.isOk();
//实际和预计比对
perform.andExpect(ok);

成功无输出

失败有提示

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /books1
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual   :404



内容请求体预期

和controller中return比较

    @Test
    void test2() throws Exception {
        MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
        ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);

        //设置预期值
        //定义预期值 content
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预计内容
        ResultMatcher ok = content.string("book");
        //实际和预计比对
        perform.andExpect(ok);

    }

成功无输出

失败有提示

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /books
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.yuhang.controller.BookController
           Method = com.yuhang.controller.BookController#getById()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
     Content type = text/plain;charset=UTF-8
             Body = books
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


java.lang.AssertionError: Response content expected: but was:
Expected :book
Actual   :books


JSON预期

实体类

@Data
public class Book {
    private Integer id;
    private String name;
    private Integer money;
}

controller

@RestController
@RequestMapping("/books")
public class BookController {

    // @GetMapping
    // public String getById(){
    //     System.out.println("getById...");
    //     return "books";
    // }

    @GetMapping
    public Book getById(){
        System.out.println("getById...");

        Book book = new Book();
        book.setId(1);
        book.setName("xiyou");
        book.setMoney(100);

        return book;
    }

}

test

@Test
void testJson() throws Exception {
    MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
    ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);

    //设置预期值
    //定义预期值 content
    ContentResultMatchers content = MockMvcResultMatchers.content();
    //预计json
    ResultMatcher ok = content.json("{\"id\":1,\"name\":\"xiyo\",\"money\":10}");
    //实际和预计比对
    perform.andExpect(ok);

}

成功无输出

失败有提示

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /books
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.yuhang.controller.BookController
           Method = com.yuhang.controller.BookController#getById()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"id":1,"name":"xiyou","money":100}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


java.lang.AssertionError: money
Expected: 10
     got: 100
 ; name
Expected: xiyo
     got: xiyou


以上可以写一起一起匹配

事务回滚

需要提交事务加@Rollback(false)

@SpringBootTest
//事务回滚
@Transactional
//提交事务
@Rollback(false)
public class TestMP {

    @Autowired
    private BookService bookService;

    @Test
    void save(){
        Book book = new Book();

        book.setName("xiyou");
        book.setMoney(100);
        bookService.save(book);
    }


}
配置文件随机值

数据层技术选型

数据源

不配置DataSource默认HikariCP

spring:
  h2:
    console:
      enabled: true
      path: /h2
  datasource:
    url: jdbc:h2:~/test
    username: sa
    password: 123456

持久化

内置持久化解决方案——JdbcTemplate

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-jdbcartifactId>
dependency>
@SpringBootTest
public class TestJdbc {

    @Test void testGetAll(@Autowired JdbcTemplate jdbcTemplate){
        String sql = "select * from tbl_book";

        // List> maps = jdbcTemplate.queryForList(sql);
        // System.out.println(maps);

        RowMapper<Book> rm = new RowMapper<Book>() {
            @Override
            public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setMoney(rs.getInt("money"));
                return book;
            }
        };
        List<Book> bookList = jdbcTemplate.query(sql, rm);
        System.out.println(bookList);
    }
    

    @Test void testJdbc(@Autowired JdbcTemplate jdbcTemplate){
        String sql = "insert into tbl_book values (3,'jdbch3',10)";
        jdbcTemplate.update(sql);
    }

数据库

<dependency>
   <groupId>com.h2databasegroupId>
   <artifactId>h2artifactId>
dependency>

<dependency>
   <groupId>org.springframework.bootgroupId>
   <artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
spring:
  h2:
    console:
      enabled: true
      path: /h2
  datasource:
    url: jdbc:h2:~/test
    username: sa
    password: 123456

网页输入http://localhost:8080/h2登录

Redis

保证Redis启动

创建springboot工程

勾选如下,下一步

yml

spring:
  redis:
    host: localhost
    port: 6379

选类型 *** 作

test

@SpringBootTest
class Springboot16RedisApplicationTests {

   @Autowired
   private RedisTemplate redisTemplate;

   @Test
   void set() {
      ValueOperations valueOperations = redisTemplate.opsForValue();
      valueOperations.set("name","yuhang");
   }

   @Test
   void get() {
      ValueOperations valueOperations = redisTemplate.opsForValue();
      Object name = valueOperations.get("name");
      System.out.println(name);//yuhang
   }

   @Test
   void hset() {
      HashOperations hashOperations = redisTemplate.opsForHash();
      hashOperations.put("hash","hh","aa");
   }

   @Test
   void hget() {
      HashOperations hashOperations = redisTemplate.opsForHash();
      Object o = hashOperations.get("hash", "hh");
      System.out.println(o);//aa
   }

}

如需使用cmd中添加的

使用StringRedisTemplate

@Test
void get2() {
   ValueOperations valueOperations = redisTemplate.opsForValue();
   Object name = valueOperations.get("name2");
   System.out.println(name);//null
}

@Test void stringTest(@Autowired StringRedisTemplate stringRedisTemplate){
   ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
   String s = valueOperations.get("name2");
   System.out.println(s);//hahah
}

使用jedis,默认lettuce

<dependency>
   <groupId>redis.clientsgroupId>
   <artifactId>jedisartifactId>
dependency>
spring:
  redis:
    host: localhost
    port: 6379
    client-type: jedis

MongoDB

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/871389.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存