[聚合文章] Spring Boot(快速入门与Swagger2与RestTemplate)

软件架构 1900-01-01 24 阅读
  • 也可以使用随机数:
  • # 随机字符串com.didispace.blog.value=${random.value}# 随机intcom.didispace.blog.number=${random.int}# 随机longcom.didispace.blog.bignumber=${random.long}# 10以内的随机数com.didispace.blog.test1=${random.int(10)}# 10-20的随机数com.didispace.blog.test2=${random.int[10,20]}
    • 可以通过:java -jar xxx.jar -- server.port = 8888 设置端口,-- 后面就是对应配置文件中的值,可以通过 SpringApplication.sendAddCommandLineProperties(false) 屏蔽命令行访问属性

    多环境配置

    • Spring Boot多环境配置文件名需要满足 application-{profile}.properties 格式,如:

      application-dev.properties:开发环境
      application-test.properties:测试环境
      application-prod.properties:生产环境

    • 然后在配置文件中通过 spring.profiles.active 属性设置生产环境,如:

      spring.profiles.active = test

    注解

    • @SpringBootApplication:等于 @Configuration + @EnableAutoConfiguration + @ComponentScan
    • @RestController:是注解@Controller和@ResponseBody的结合,默认返回JSON
    • @Configuration:注解在类上,标记该类是一个配置类
    • @EnableAutoConfiguration:注解在配置类上、根据导入@EnableConfigServer的包自动配置 Spring Boot
    • @ComponentScan:注解在配置类上,扫描指定包下的所有类,将其注入IOC容器
    • @EntityScan:注解在入口类上,扫描指定包下的实体类
    • @ControllerAdvice:声明统一异常处理类
    • @ExceptionHandler:注解在方法上,声明对哪些异常进行处理
    • @EnableAutoConfiguration:注解在类上,让 spring boot 根据依赖项对 spring 进行自动配置,如添加了 spring-boot-starter-web 则配置 SpringMVC
    • @GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping:简化HTTP方法映射,更好的表达注解方法语义
    • @Order:控制配置类的加载顺序
    @Configuration@Order(2)public class Demo1Config {    @Bean    public Demo1Service demo1Service(){        System.out.println("demo1config 加载了");        return new Demo1Service();    }}
    @Configuration@Order(1)public class Demo2Config {    @Bean    public Demo2Service demo2Service(){        System.out.println("demo2config 加载了");        return new Demo2Service();    }}
    输出结果:demo2config 加载了、demo1config 加载了
    • @ConfigurationProperties:可以将配置信息自动映射到实体类上,类似@Valid
    connection.username=adminconnection.password=kyjufskifas2jsfsconnection.remoteAddress=192.168.1.1
    @Component@Data@ConfigurationProperties(prefix="connection")public class ConnectionSettings {    private String username;    private String remoteAddress;    private String password ;}

    异常处理返回JSON

    1. 创建返回的JSON对象:code(消息类型),message(消息内容),url(请求url),data(请求返回数据)
    public class ErrorInfo<T> {    public static final Integer OK = 0;    public static final Integer ERROR = 100;    private Integer code;    private String message;    private String url;    private T data;    // 省略getter和setter}
    1. 创建自定义异常类
    public class MyException extends Exception {    public MyException(String message) {        super(message);
                    

    注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。