Servlet 生命周期的注解
@PostConstruct 和@PreDestroy
package com.example.demo.config; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Configuration public class MyConfig { public MyConfig(){ System.out.println("MyConfig"); } @PostConstruct // 项目启动的时候执行方法 public void init(){ System.out.println("PostConstruct"); } @PreDestroy // 释放 bean 所持有的资源 public void destroy(){ System.out.println("destroy"); } }
读取配置文件
application.properties
# 自定义配置 person.name=Tom person.age=23
接收配置
package com.example.demo.bean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "person") // 指定前缀
@Data
public class PersonBean {
private String name;
private Integer age;
}
控制器
package com.example.demo.controller; import com.example.demo.bean.PersonBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonController { @Autowired PersonBean personBean; @GetMapping("/person") public PersonBean person(){ return this.personBean; } }
测试接口读取配置
GET http://localhost:8080/person { "name": "Tom", "age": 23 }
异常处理
定义异常处理
package com.example.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { @ExceptionHandler public ResponseEntity<Map<String, Object>> exceptionHandler(Exception e){ Map<String, Object> data = new HashMap<>(); data.put("errMsg", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(data); } }
抛出异常
package com.example.demo.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; @RestController public class ExceptionController { @GetMapping("/exception") public void exception(){ throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "不对"); } }
自定义异常处理实践
ErrorCode 异常枚举类
ErrorResponse 异常返回数据
BaseException 自定义异常基类
ResourceNotFoundException 资源未找到
GlobalExceptionHandler 全局异常处理
ExceptionController 异常测试
package com.example.demo.exception; import org.springframework.http.HttpStatus; /** * 错误枚举类 */ public enum ErrorCode { UNKNOWN_EXCEPTION(1000, HttpStatus.BAD_REQUEST, "未知错误"), RESOURCE_NOT_FOUND(1001, HttpStatus.NOT_FOUND, "未找到该资源"), REQUEST_VALIDATION_FAILED(1002, HttpStatus.BAD_REQUEST, "请求数据格式验证失败"); private final int code; // 异常码 private final HttpStatus status; // http状态码 private final String message; // 提示消息 ErrorCode(int code, HttpStatus status, String message) { this.code = code; this.status = status; this.message = message; } public int getCode() { return code; } public HttpStatus getStatus() { return status; } public String getMessage() { return message; } }
package com.example.demo.exception; public class ErrorResponse { private int code; private int status; private String message; public ErrorResponse() { } public ErrorResponse(int code, int status, String message) { this.code = code; this.status = status; this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } package com.example.demo.exception; public abstract class BaseException extends RuntimeException { private final ErrorCode error; public BaseException(ErrorCode error) { this.error = error; } public ErrorCode getError() { return error; } } package com.example.demo.exception; public abstract class BaseException extends RuntimeException { private final ErrorCode error; public BaseException(ErrorCode error) { this.error = error; } public ErrorCode getError() { return error; } } package com.example.demo.exception; public class ResourceNotFoundException extends BaseException{ public ResourceNotFoundException() { super(ErrorCode.RESOURCE_NOT_FOUND); } } package com.example.demo.exception; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { // 自定义异常处理 @ExceptionHandler({BaseException.class}) public ResponseEntity<ErrorResponse> baseExceptionHandler(BaseException e){ ErrorResponse response = new ErrorResponse(); response.setCode(e.getError().getCode()); response.setStatus(e.getError().getStatus().value()); response.setMessage(e.getError().getMessage()); return ResponseEntity.status(e.getError().getStatus()).body(response); } // 其他异常处理 @ExceptionHandler public ResponseEntity<ErrorResponse> exceptionHandler(Exception e){ ErrorResponse response = new ErrorResponse(); response.setCode(ErrorCode.UNKNOWN_EXCEPTION.getCode()); response.setStatus(ErrorCode.UNKNOWN_EXCEPTION.getStatus().value()); response.setMessage(ErrorCode.UNKNOWN_EXCEPTION.getMessage()); return ResponseEntity.status(ErrorCode.UNKNOWN_EXCEPTION.getStatus()).body(response); } } package com.example.demo.controller; import com.example.demo.exception.ResourceNotFoundException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ExceptionController { @GetMapping("/resourceException") public void resourceException(){ throw new ResourceNotFoundException(); } @GetMapping("/exception") public void exception(){ throw new RuntimeException(); } }