1. 程式人生 > >Spring Boot入門系列三(資源文件屬性配置)

Spring Boot入門系列三(資源文件屬性配置)

response mage 註意 site spa website 圖片 process ram

  Spring Boot 資源文件屬性配置  

  配置文件是指在resources根目錄下的application.propertiesapplication.yml配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。

在pom.xml中添加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

一、資源文件屬性配置直接讀取

/**
 * @author oyc
 * @Title:
 * @Description:
 * @date 2018/6/1321:44
 */
@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Value("${com.bestoyc.opensource.name}")
    private String name;

    @Value("${com.bestoyc.opensource.webSite}")
    private String webSite;

    @Value("${com.bestoyc.opensource.language}")
    private String language;

    @RequestMapping("/getResource1")
    public String GetResource1() {
        return "Name:" + name + "----WebSite:" + webSite + "----Language:" + language;
    }
}

  註意:在@Value的${}中包含的是核心配置文件中的鍵名。在Controller類上加@RestController表示將此類中的所有視圖都以JSON方式顯示,類似於在視圖方法上加@ResponseBody

二、資源文件中的屬性配置映射到實體類中

  將配置屬性映射到實體類中,然後再將實體類註入到Controller或者Service中即可完成屬性配置的讀取。

  屬性配置文件(resource.properties):

com.bestoyc.opensource.name=bestoyc
com.bestoyc.opensource.website=www.bestoyc.com
com.bestoyc.opensource.language=java

    技術分享圖片

  對應的實體類(Resource.java):

/**
 * @author oyc
 * @Title:資源文件映射實體類
 * @Description:
 * @date 2018/6/13 21:32
 */
@Configuration
@ConfigurationProperties(prefix = "com.bestoyc.opensource")
@PropertySource(value = "classpath:resource.properties")
public class Resource {
    private String name;
    private String webSite;
    private String language;

  //省略getter、setter方法
}

註意:

  • @ConfigurationProperties註釋中有兩個屬性:

    • locations:指定配置文件的所在位置
    • PropertySource:指定配置文件中鍵名稱的前綴(我這裏配置文件中所有鍵名都是以com.bestoyc.opensource開頭)

    技術分享圖片

  測試類(ResourceController.java):

/**
 * @author oyc
 * @Title:
 * @Description:
 * @date 2018/6/1321:44
 */
@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private Resource resource;


    @RequestMapping("/getResource")
    public String GetResource() {
        return "Name:" + resource.getName() + "----WebSite:" + resource.getWebSite() + "----Language:" + resource.getLanguage();
    }
}

  在SpringdemoApplication中加入@ComponentScan(basePackages= {"com.bestoyc"}),用於掃描我們的測試Controller包中的測試類方法:

   技術分享圖片

訪問:http://localhost:8080/resource/getResource 時將得到Name:java----WebSite:www.bestoyc.com----Language:java

  技術分享圖片

Spring Boot入門系列三(資源文件屬性配置)