1. 程式人生 > >第一個spring-boot項目

第一個spring-boot項目

www spa OS entity eof acl ati led www.

1.配置文件  application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521:xe
username: system
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true

1.讀取配置文件的內容.

server:
  port: 8081
  context-path: /boot

service:
  name: freya
version: 1.1

(1).@Value("${service.name}")

private String name ;

(2).使用Environment,env.getProperty("鍵名")

@Autowired
    private Environment env;

    @RequestMapping(value = "/hello")
    public String hello() {
        return "hello spring boot! " + env.getProperty("service.name");
    }
(3)
自定義一個實體類
@Component
@ConfigurationProperties(prefix = "project")  //配置文件中前綴
@PropertySource(value = "classpath:config/config.properties") //文件位置
public class MyConfig {
    private String version;
    private String name;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
在controller中獲取
RestController
public class HelloController {

    @Autowired
    private MyConfig myConfig;

    @RequestMapping(value = "/hello")
    public String hello() {
        return "hello spring boot! " myConfig.getVersion() + " " +  myConfig.getName() ;
    }
}

2.表單提交

controller層
@PostMapping("/save")
public Girl save(@Valid Girl girl, BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.print(bindingResult.getFieldError().getDefaultMessage());
return null;
}
girl.setAge(girl.getAge());
girl.setCupSize(girl.getCupSize());
girl.setMoney(girl.getMoney());
return girlRepository.save(girl);
}

實體類

@Entity  //對應數據庫中的表
public class Girl{

@Id //主鍵
@GeneratedValue 自增,從1開始
private Integer id;

@Min(value = 18,message = "未成年") //最小值為18,不滿足返回message的值
private Integer age;
private String cupSize;

@Min(value = 0,message = "金額必傳")
private Double money;

3.自定義異常 (codeEnum為枚舉類型,方便管理異常狀態碼與返回信息)

public class GirlException extends RuntimeException{
private String respCode;

public GirlException(CodeEnum codeEnum) {
super(codeEnum.getMsg());
this.respCode = codeEnum.getCode();
}
public GirlException(String message,String code) {
super(message);
this.respCode = code;
}
public String getRespCode() {
return respCode;
}

public void setRespCode(String respCode) {
this.respCode = respCode;
}
}

//枚舉實體public enum CodeEnum {
    ERROR_CODE("-1","系統異常"),
OK_CODE("0","OK"),
PRE_SCHOOL("100","你可能還在上小學吧"),
HIGH_SCHOOL("101","你可能還在上中學吧");

CodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;

public String getCode() {
return code;
}

public String getMsg() {
return msg;
}
}
/**
 * 捕捉異常類  (handle)
*/
@ControllerAdvice
public class ExceptionHandle {

@ExceptionHandler
@ResponseBody
public ResultMap handle(Exception e){
if(e instanceof GirlException){
GirlException girlException = (GirlException) e;
return ResultMap.error(girlException.getRespCode(),girlException.getMessage(),"");
}
return ResultMap.error(e.getMessage());
}
}

/**
* spring-boot ao
*/
@Aspect
@Component
public class HttpAspect {

private static final Logger log = LoggerFactory.getLogger(HttpAspect.class); //spring中自帶的日誌包

@Pointcut("execution(* com.girl.controller.GirlController.*(..))")
public void log(){}

@Before("log()")
public void log1(){
//獲取request請求
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
log.info("id={}",request.getRemoteAddr()); //日誌信息將輸出在{}中

}
}

多模塊部署:
https://www.imooc.com/video/16354

第一個spring-boot項目