3.6-Spring-Boot

优质
小牛编辑
126浏览
2023-12-01

1.1 步骤

  • 新建项目:【File】——>【New】——>【Project】——>【Spring Initializr】
  • 配置。
参数功能示例默认值
server.port配置服务端口。80818080
server.context-path(server.servlet.context-path)配置服务总路径。/hello/
  • 新建 Controller,标注 @RestController。
  • 多环境配置
参数功能示例
spring.profiles.active配置代码使用的配置文件。dev,使用 application-dev.yml。

2. 集成持久化层框架

2.1 SQL

参数功能示例
spring.datasource.url配置 ip 和 数据库。mysql jdbc:mysql://\:\/db
spring.datasource.username配置用户名称。
spring.datasource.password配置用户密码。
spring.datasource.driver-class-name配置数据库驱动。com.mysql.jdbc.Driver

2.1.1 Jpa

  • 添加依赖。 test-springboot-jpa-pom.xml
  • Jpa 配置
参数功能示例
spring.jpa.hibernate.ddl-auto(1)create:每次程序重启根据实体类创建新表,覆盖旧表;(2)update:不删除数据;(3)create-drop:应用停止时删除表;(4)none,默认啥都不做;(5)validate验证表结构与实体类结构是否一致,不一致则报错。
spring.jpa.show-sqltrue
  • 编写实体类。

  • Entity 类注解

注解功能
@Entity注解在实体类头部,name属性定义数据库中的表名。
@ID标志实体中的属性为主键。
@GeneratedValue注解主键属性值自动生成。
@Column注解成员变量,和数据库中的列映射,name属性定义数据库中的列名。
@Data省略 Getter/Setter 方法。
  • 新建 XXXRepository 继承 JpaRepository。
  • 常见 Repository 接口功能。
接口方法功能
CrudRepositorysave
saveAll
findByID
findAll
findAllByID
existsById
delete
deleteById
deleteAll
deleteAll(Iterable<? extends T> var1)
count
JpaSpecificationExecutor
  • Repository 类注解
注解功能
@Query标注Repository类中的查询语句。
@Param标注函数传入Sql语句中的参数名。
@Modifying
  • Controller 类中注入调用 Service 类中的方法,Service 类中注入调用 Repository 类中的方法。

2.1.2 MyBatis

2.1.3 使用步骤

  • 添加依赖 test-springboot-mybatis-pom.xml
  • 在 resource 目录下添加 mybatis-generator.xml
  • 在 【Run】——>【Edit Configurations】 中添加 Maven 命令,mybatis-generator:generate并运行。
  • 生成 Dao 测试类,添加@MapperScan("com.iecas.testspringbootmybaties.dao") 注解。

2.2 NoSQL

2.2.1 Redis

2.2.2 MongoDB

2.2.3 ElasticSearch

3. Web 层(包括 Controller 和 Service 层)

3.1 URL 映射和参数传递

注解功能
@RequestMapping配置 URL 类和方法映射
@GetMapping在Get方法头使用。
@PostMapping在Post方法头使用。
@PathVariable获取URL中的数据。
@RequestParam获取请求参数的值。
参数直接使用实体对象。
@RestController
@RequestMapping("/hello")
@Slf4j
public class HelloController {

    /**
     * http://localhost:8081/hello/setId/1
     * @param id
     * @return
     */
    @GetMapping("/setId/{id}")
    public String say(@PathVariable("id") int id){
        return "id:"+id;
    }

    /**
     * http://localhost:8081/hello/setId1?id=1
     * @param id
     * @return
     */
    @GetMapping("/setId1")
    public String say1(@RequestParam(value = "id",required = false,defaultValue = "0") int id){
        return "id:"+id;
    }


    /**
     * 接收 json 参数
     * @param girl
     * @return
     */
    @PostMapping("/setGirl")
    public String say(@RequestBody  Girl girl){
        log.info("CupSize:{}",girl.getCupSize());
        return "OK";
    }

    /**
     * 接收多个参数
     * @param girl
     * @return
     */
    @PostMapping("/setGirl1")
    public String say1(Girl girl){
        log.info("CupSize:{}",girl.getCupSize());
        return "OK";
    }
}

3.2 表单验证

  • 使用 @Min注解属性值的限定条件和错误信息。
  • 使用 @Valid 注解要进行验证的对象。
  • 传入 BindingResult 对象 bindingResult。
  • 使用 bindingResult.getFieldError().getDeafaultMessage() 方法获取错误信息。

3.3 Eception的统一异常处理

  • 新建 ExceptionHandler 类,该类使用 @RestControllerAdvice 注解。
  • 获取 Exception 对象,根据 Exception 的 code 值,判断异常的类型,多种异常状态使用枚举类型封装。
  • 将不同的 code 和 message 封装进 Result,返回给前端,并将非GirlException在控制台上打印日志。
  • GirlException继承RuntimeException,在构造器中初始化父类。

    3.4 整合 Spring Security

    3.5 整合 JackSon 统一返回值格式

    3.5.1 使用步骤

  • 3.5.1.1 常用注解

    |注解|功能| |------|------| |@jsonview|处理数据库中属性名和Json数据属性不同名问题。| |@||

    3.6 事务

    3.6.1 使用步骤

    使用 @Transactional 标注在方法头,该方法的数据库操作便具有事务性。

4. 跨层通用

4.1 注入

注解功能
@Component@Repository、@Service和@Controller的通用形式,将类注入为Bean,只有该类加上该注解,才能被@Autowired。
@Controller处理 http 请求。
@RestControllerSpring4 之后新加的注解,相当于 @Controller+@ResponseBody。
@Service标注 Service类。
@Repository标注 Jpa、Hibernate 和 Mybatis 中的 Repository 类。
@Autowired如在Controller中注入Service,在Service中注入Repository。
@Value将配置文件中的内容注入属性变量。
@ConfigurationProperties读取配置文件里的属性值,和@Component 结合使用。

4.2 AOP

  • 添加依赖
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
     <version>2.0.5.RELEASE</version>
    </dependency>
    
  • 建立处理文件 Aspect
  • 给 Aspect 类添加 @Aspect,@Component 注解

4.3 日志

参数功能
@Slf4j定义在类中使用日志。

参考资料