SpringBoot 系列教程(配置文件使用)

本例描述

經過如下範例,能夠快速上手使用SpringBoot框架。來一個配置文件使用properties小工程。web

開發工具

本系列教程均採用 IDEA 做爲開發工具,JDK 爲 1.8spring

測試工具

本例可以使用 PostMan工具來進行測試。PostMan 官網地址 可進行下載。app

開發步驟

  1. 打開IDEA,建立工程 Properties(此處截圖省略);
  2. 在POM文件中添加以下代碼內容
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
  1. 建立包結構信息 com.test.properties.controller(存放控制器代碼) 、 com.test.properties.pros(存放屬性代碼)、com.test.properties.app(存放啓動類代碼)框架

  2. 建立控制器類 PropertiesController 類,代碼以下ide

@RestController
public class PropertiesController {

    @Autowired
    private HomeProperties homeProperties;

    @RequestMapping("/")
    public String sayHomeProperties(){
        return homeProperties.toString();
    }
}

HomeProperties 類爲自定義類,下文中會出現spring-boot

  1. 建立屬性類 HomeProperties 類,代碼以下:
@Component
@ConfigurationProperties(prefix = "home")
public class HomeProperties {

    /**
     * ID
     */
    private int id;

    /**
     * NAME
     */
    private String name;

    /**
     * AGE
     */
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return this.getId() + " " + this.getName() + " " + this.getAge();
    }
}

註解@ConfigurationProperties,表示讀取配置文件前綴會自動進行匹配,本範例中配置爲home,當配置文件中出現home開頭的屬性就會自動和當前類中的屬性進行匹配。如屬性文件中 home.id ,類中id屬性就會自動關聯。工具

  1. 建立啓動類 Application 類,代碼以下
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 添加屬性資源配置文件 在resources目錄下新增以下文件: 文件一:application.properties 、文件二:application-dev.properties 文件一中寫入以下內容:
## 生產環境配置文件選項
spring.profiles.active=dev

文件二中寫入以下內容:post

## config info (生產環境)
home.id=1001
home.name=Test
home.age=25
  1. 啓動應用,訪問 http://localhost:8080 系統會根據配置文件內容進行反饋。
相關文章
相關標籤/搜索