spring-boot 一些知识点


请求参数注解

  • @PathVariable(“name”) 解析请求地址里面的参数 restful形式
  • @RequestParam()可以定义请求参数的name,设置defaultValue 和是否必须 require=true
  • @RequestBody 使用的时候需要请求的content-type为application/json 且用body传输数据
  • @RequestHeader(“access_token”) 解析请求header里面的内容

jackson 的注解使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class User {
//空的话不反回
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer age;
//别名
@JsonProperty("account")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
private String address;
//不序列化字段 忽略
@JsonIgnore
private String pwd;
//日期格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" ,timezone = "GMT+8")
private Date createTime;

//getter setter
}

资源加载

  • 加载静态资源顺序:META/resources > resources > static > public

  • 如果要加载自定义的文件夹里面的内容 需要在配置文件中配置

    1
    spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
  • html文件如果放在template目录下 需要使用thymeleaf等模板 然后有controller跳转过去

如果需要直接访问html需要将文件放在上面静态资源加载的目录中

文件上传

  • MultipartFile 接收文件 form表单提交 需要声明enctype 类型为 multipart/form-data

  • 使用MultipartFile 的transferTo(File) 方法生成文件

  • 上传文件大小的限制 (下面的1024等应该放到配置文件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 public class FileUploadConfig {

@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件大小
factory.setMaxFileSize(DataSize.ofKilobytes(1024));
//总上传数据大小
factory.setMaxRequestSize(DataSize.ofKilobytes(1024*10));

return factory.createMultipartConfig();
}

}
  • jar包后怎么访问 需要将访问地址(file:…)设置到静态文件加载里面
1
2
web.upload-path=E:\\
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}

IDEA 热加载设置

  • 引入依赖 spring-boot-devtools

  • 打开 Settings –> Build-Execution-Deployment –> Compiler,将 Build project automatically勾上

  • 点击 Help –> Find Action,或使用快捷键 Ctrl+Shift+A来打开 Registry...,将 其中的compiler.automake.allow.when.app.running勾上

  • 推荐使用trigger文件去控制是否重启

    1
    spring.devtools.restart.trigger-file=.trigger

properties值的获取

  • 值定义在application.properties里面直接使用@Value注入,如果是自定义的properties,则需要在组件加上@PropertySource注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Controller
    @PropertySource({"classpath:config/file-config.properties"})
    public class PageController {
    //file-config.properties
    @Value("${file.name}")
    private String ala;
    //application.properties 里面
    @Value("${my.test.code}")
    private String code;
    }
  • 使用Environment获取,在组件中注入Environment后,调用Environment.getProperty()方法

  • 自定义类的形式

    1.application.properties 加入key-value值

    1
    2
    server.serverName=spring boot
    server.serverPort=9800

    2.自定义类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @Component
    @ConfigurationProperties(prefix = "server")
    //下面是指定的文件
    //@PropertySource({"classpath:config/file-config.properties"})
    public class ServerProperties {


    private String serverName;

    private String serverPort;

    public String getServerName() {
    return serverName;
    }

    public void setServerName(String serverName) {
    this.serverName = serverName;
    }

    public String getServerPort() {
    return serverPort;
    }

    public void setServerPort(String serverPort) {
    this.serverPort = serverPort;
    }
    }

    3.注入使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @RestController
    public class PropertyController {

    @Autowired
    private ServerProperties serverProperties;

    @GetMapping("/getProps")
    public String getProps(){
    return serverProperties.getServerName()+":"+serverProperties.getServerPort();
    }

    }

异常处理

  • 全局异常-返回json 使用@RestControllerAdvice 和 @ExceptionHandler(Exception.class) 注解,CustomErrorType类为自己定义的pojo类,具体见代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    @RestControllerAdvice
    //@ControllerAdvice
    public class ExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    //@ResponseBody
    CustomErrorType handleControllerException(Exception e, HttpServletRequest request){
    return new CustomErrorType(500,e.getMessage());
    }
    //官方文档
    // @ExceptionHandler(Exception.class)
    // ResponseEntity<?> handleException(HttpServletRequest request,Throwable e){
    // HttpStatus status = getStatus(request);
    //
    // return new ResponseEntity<>(new CustomErrorType(status.value(),e.getMessage()),status);
    // }
    //
    //
    //
    // private HttpStatus getStatus(HttpServletRequest request){
    // Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
    // if(statusCode==null){
    // return HttpStatus.INTERNAL_SERVER_ERROR;
    // }
    // return HttpStatus.valueOf(statusCode);
    // }


    }
  • 自定义异常 以及返回 页面(需要pom.xml中加入thymeleaf依赖)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @ExceptionHandler(MyException.class)
    Object handleMyException(MyException e,HttpServletRequest request){
    //返回json数据
    //return new CustomErrorType(500,e.getMessage());
    //返回页面
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("500");
    modelAndView.addObject("code","500");
    return modelAndView;
    }

打成war包运行

  • pom.xml中加入package类型为war

    1
    2
    3
    4
    5
    6
    7
      
    <artifactId>learn-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>learn-spring-boot</name>
    <description>Demo project for Spring Boot</description>
    <!--打包方式-->
    <packaging>war</packaging>
  • pom.xml加入maven构建插件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <build>
    <finalName>l-spring-boot</finalName>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>
  • 修改启动类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @SpringBootApplication
    public class LearnSpringBootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(LearnSpringBootApplication.class);
    }

    public static void main(String[] args) {
    SpringApplication.run(LearnSpringBootApplication.class, args);
    }

    }