美文网首页
Spring Boot

Spring Boot

作者: 王龙江_3c83 | 来源:发表于2019-03-19 10:14 被阅读0次

1. HelloWorld

1.1 步骤

  • 新建项目:【File】——>【New】——>【Project】——>【Spring Initializr】
  • 配置。
参数 功能 示例 默认值
server.port 配置服务端口。 8081 8080
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://<host>:<port>/db
spring.datasource.username 配置用户名称。
spring.datasource.password 配置用户密码。
spring.datasource.driver-class-name 配置数据库驱动。 com.mysql.jdbc.Driver

2.1.1 Jpa

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

  • Entity 类注解

注解 功能
@Entity 注解在实体类头部,name属性定义数据库中的表名。
@ID 标志实体中的属性为主键。
@GeneratedValue 注解主键属性值自动生成。
@Column 注解成员变量,和数据库中的列映射,name属性定义数据库中的列名。
  • 新建 XXXRepository 继承 JpaRepository<Entity,Id>。
  • 常见 Repository 接口功能。
接口 方法 功能
CrudRepository save
saveAll
findByID
findAll
findAllByID
existsById
delete
deleteById
deleteAll
deleteAll(Iterable<? extends T> var1)
count
JpaSpecificationExecutor
  • Repository 类注解
注解 功能
@Query 给 Repository 类中的方法设置查询语句。
@Param 标注函数传入Sql语句中的参数名。
@Modifying
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);
@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);
  • 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") 注解。

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

3.1 URL 映射和参数传递

注解 功能
@RequestMapping 配置 URL 类和方法映射
@GetMapping 在Get方法头使用。
@PostMapping 在Post方法头使用。
@PathVariable 获取URL中的数据。
@RequestParam 获取请求参数的值。
@RequestBody 获取 Post 请求的实体对象。
@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 请求。
@RestController Spring4 之后新加的注解,相当于 @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 定义在类中使用日志。

参考资料

实战代码

相关文章

网友评论

      本文标题:Spring Boot

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