美文网首页
23.SpringBoot

23.SpringBoot

作者: 星野君 | 来源:发表于2022-05-05 14:59 被阅读0次

一、快速入门

  • 新建模块


    image.png
  • 勾选模块


    image.png
  • 编写对应的controller层
package com.ylf.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/students")
public class StudentController {
  @GetMapping("/{id}")
  public String all(@PathVariable Integer id) {
    System.out.println("xxxx");
    return "hello";
  }
}

执行Application启动tomcat服务器,测试...

  • 程序快速启动
  1. 项目打包
  2. 在jar包目录下输入cmd
java -jar 文件名

二、读取yml

  • 第一第二种方式
public class StudentController {
  @Value("${service.port}")
  private String port;

  @Autowired private Environment environment;

  @GetMapping("/{id}")
  public String all(@PathVariable Integer id) {
    System.out.println(port);
    System.out.println(environment.getProperty("service.port"));
    return "hello";
  }
}
  • 第三种方式
  1. 创建一个实体类,属性和yml文件里的值对应
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
// 属性方法...
}
public class StudentController {

  @Autowired private Enterprise enterprise;

  @GetMapping("/{id}")
  public String all(@PathVariable Integer id) {
    System.out.println(enterprise);
    return "hello";
  }
}

三、多环境开发

#设置默认的环境

spring:
  profiles:
    active: test

---
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 80
---
spring:
  config:
    activate:
      on-profile: pro
server:
  port: 81
---
spring:
  config:
    activate:
      on-profile: test
server:
  port: 82
java -jar 文件名 --spring.profiles.active=环境名

四、整合mybatis

  1. 创建模块,勾选


    image.png
  2. 修改application.yml文件
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db02
    username: root
    password: 123

  1. 添加@Mapper注解
@Mapper
public interface StudentDao {
  @Select("select * from student where id = #{id}")
  Student findAll(Integer id);
}
  1. 测试
package com.ylf;

import com.ylf.dao.StudentDao;
import com.ylf.domain.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot02ApplicationTests {
  @Autowired private StudentDao studentDao;

  @Test
  void contextLoads() {
    final Student all = studentDao.findAll(1);
    System.out.println(all);
  }
}

  1. 使用第三方数据源
  • 导入坐标,然后加一个type就可以了
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db02
    username: root
    password: 123
    type: com.alibaba.druid.pool.DruidDataSource

相关文章

  • 23.SpringBoot

    一、快速入门 新建模块image.png 勾选模块image.png 编写对应的controller层 执行App...

网友评论

      本文标题:23.SpringBoot

      本文链接:https://www.haomeiwen.com/subject/hjqsyrtx.html