1. 程式人生 > 實用技巧 >框架 Spring Boot 技術入門到整合 5-1 Springboot 類讀取配置檔案

框架 Spring Boot 技術入門到整合 5-1 Springboot 類讀取配置檔案

0    課程地址

https://www.imooc.com/video/16718/0

1    讀取配置檔案demo
1.1  引入依賴
<!-- 載入配置檔案,引入依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>
true</optional> </dependency>

1.2  新增配置檔案

resource.properties

com.imooc.openresource.name=imooc
com.imooc.openresource.website=www.imooc.com
com.imooc.openresource.language=java

1.3  新增實體類bean
package com.example.demo.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * Resource * * @author 魏豆豆 * @date 2020/11/21 */ @Configuration//會引入資原始檔 @PropertySource(value="classpath:resource.properties")//引入資原始檔的地址 @ConfigurationProperties(prefix = "com.imooc.openresource")//
字首 public class Resource { private String name; private String website; private String language; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }

1.4  Controller類呼叫
package com.example.demo.son.democ;

import com.example.demo.bean.Resource;
import com.example.demo.tools.JSONResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * ResourceController
 *
 * @author 魏豆豆
 * @date 2020/11/21
 */
@RestController
public class ResourceController {
    @Autowired//自動裝配,通過該註解可以消除get和set方法
    private Resource resource;


    @RequestMapping("/getResource")
    public JSONResult getResourceController(){
        Resource bean = new Resource();
        BeanUtils.copyProperties(resource,bean);
        return JSONResult.ok(bean);
    }
}

1.5  列印

2    常用註解
@Configuration//會引入資原始檔
@PropertySource(value="classpath:resource.properties")//引入資原始檔的地址
@ConfigurationProperties(prefix = "com.imooc.openresource")//字首
@Autowired//自動裝配,通過該註解可以消除get和set方法