Spring Boot學習(二):配置文件

前言

Spring Boot有兩中類型的配置文件:.properties和.yml。Spring Boot默認的全局配置文件名爲application.properties或者application.yml(spring官方推薦使用的格式是.yml格式,目前官網都是實例都是使用yml格式進行配置講解的),應用啓動時會自動加載此文件,無需手動引入。web

方式1:經過配置綁定對象的方式

我自定義一個配置文件my.propertiesspring

student.name = ZhangSan
student.age = ${random.int[1,30]}
student.parents[0] = ZhangMing
student.parents[1] = XiaoHua

建立一個Bean,用於自動讀取配置文件的內容(注:需保證與配置文件的字段一致)springboot

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by Administrator on 2018/9/28.
 */
@Component
@PropertySource(value = "classpath:/my.properties", encoding="utf-8") //設置系統加載自定義的配置文件,並指定配置文件編碼格式
@ConfigurationProperties(prefix = "student")
@Data
public class Student {

    private String name;

    private int age;

    private List<String> parents;
}
import com.jc.testConf.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2018/6/26.
 */
@RestController
public class HelloController {

    @Autowired
    Student student;

    @RequestMapping("/testConf")
    private String getStudent(){
        return student.toString();
    }

}

測試,果真可以獲取到配置文件的數據

因此,之後,就可經過配置對象來獲取相關的配置便可。app

方式2:@Value("${blog.author}")的形式獲取屬性值

import com.jc.testConf.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2018/6/26.
 */
@RestController
public class HelloController {

    @Value(value = "${student.name}")
    String name;

    @RequestMapping("/studentName")
    private String studentName(){
        return name;
    }

}

測試能夠獲取
dom

相關說明

在學習配置中,設計到其餘的知識點,全部在文章末尾補充下。學習

註解@Value的說明

有三種使用方式:測試

  • 基本數值的填充,如:@Value("12")、@Value("張三")
  • 基於SpEl表達式#{} 如上文中年齡也能夠這樣#{28-2},如:@Value("#{car.luntai}")
  • 基於配置文件${配置文件中參數名},如:@Value("${database.source.url}")

參考

https://blog.lqdev.cn/2018/07/14/springboot/chapter-third/
http://blog.51cto.com/4247649/2118348編碼

相關文章
相關標籤/搜索