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



创建项目

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

工具经典方法:

1

选择JDK时,建议1.8

image-20220505081833730

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

image-20220505082240945

web工程

image-20220505082344728

mybatis,如使用mybatis-plus手动pom

image-20220505082425813

选择好所需,下一步

image-20220505082540772

image-20220505082635280

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

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

image-20220505082851879

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

image-20220505083141342

启动类出错

image-20220505083701365

IDEA没有加载启动类?

打开启动类,等待spring管理

image-20220505084011724

然后运行就好了

打包速度

关闭test

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

image-20220505084200577

数据库配置

链接失败密码问题

测试多种组合

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

image-20220505084533366

例子:

dataSource:
  password: 9.

测试类

@SpringBootTest
class Springboot13ConfigurationApplicationTests {

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

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

}

image-20220505172832140

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

mybatis-plus

表的匹配和id自增

image-20220505085053784

拦截器

配置分页拦截器

@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使用全路径

image-20220505085225489

校验

<!--1.导入JSR303规范-->
<dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
</dependency>

实体类

//2.开启校验
@Validated
public class ServletConfig {
    private String ipAddress;
    //3.设置校验规则
    @Max(value = 100,message = "最大值不该超过100")
    private int port;
    private long timeout;
}
<!--4.使用hibernate框架提供校验器做实现类-->
<dependency>
   <groupId>org.hibernate.validator</groupId>
   <artifactId>hibernate-validator</artifactId>
</dependency>

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

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

超过提示

image-20220505171539774

计量单位

实体类

@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);

image-20220505191537760

heiam

临时专用属性

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

方法一:

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

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

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

image-20220505182920058

方法二:

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

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

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

image-20220505183332132

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);
    }

}

image-20220505185510266

测试类

随机端口

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestWeb {

    @Test
    void test(){

    }
}

image-20220505191426050

发送虚拟请求

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);
    }
}

image-20220506172714098

设置预期值

状态预期

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
<Click to see difference>


内容请求体预期

和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:<book> but was:<books>
Expected :book
Actual   :books
<Click to see difference>

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

<Click to see difference>

以上可以写一起一起匹配

事务回滚

需要提交事务加@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);
    }


}

配置文件随机值

image-20220506183344770

数据层技术选型

数据源

image-20220506222749916

不配置DataSource默认HikariCP

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

持久化

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

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

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

        // List<Map<String, Object>> 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.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency>

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

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

image-20220506223541171

Redis

保证Redis启动

image-20220507101351830

创建springboot工程

勾选如下,下一步

image-20220507095108834

yml

spring:
  redis:
    host: localhost
    port: 6379

选类型操作

image-20220507101116410

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

image-20220507101652723

image-20220507102005534

@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.clients</groupId>
   <artifactId>jedis</artifactId>
</dependency>
spring:
  redis:
    host: localhost
    port: 6379
    client-type: jedis

image-20220507103907458

MongoDB

image-20220507112053838

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就爱喝菠萝啤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值