IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 【Springboot】springboot使用记录[个人版] -> 正文阅读

[Java知识库]【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

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-05-08 07:54:26  更:2022-05-08 07:55:07 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 0:18:14-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码