Spring Boot教學
Spring Boot是什麼?
Spring Boot簡介
Spring Boot主要目標
Spring Boot快速入門
新項目爲什麼需要Spring Boot?
Spring Boot引導過程
Spring Boot核心和限制
Spring Boot Tomcat部署
Spring Boot優點和缺點
Spring Boot構建系統
Spring Boot入門
Spring Boot代碼結構
Spring Boot安裝
Spring Boot Bean和依賴注入
Spring Boot應用程序開發入門
Spring Boot運行器(Runner)
Spring Boot JSP應用實例
Spring Boot應用程序屬性
Spring Boot將WAR文件部署到Tomcat
Spring Boot日誌
Spring Boot Hello World(Thymeleaf)示例
Spring Boot構建RESTful Web服務
Spring Boot非web應用程序實例
Spring Boot異常處理
Spring Boot @ConfigurationProperties實例
Spring Boot攔截器
Spring Boot SLF4J日誌實例
Spring Boot Servlet過濾器
Spring Boot Ajax實例
Spring Boot Tomcat端口號
Spring Boot文件上傳示例(Ajax和REST)
Spring Boot Rest模板
Spring Boot文件上傳示例
Spring Boot文件處理
Spring Boot服務組件
Spring Boot Thymeleaf示例
Spring Boot使用RESTful Web服務
Spring Boot CORS支持
Spring Boot國際化
Spring Boot調度
Spring Boot啓用HTTPS
Spring Boot Eureka服務器
Spring Boost Eureka服務註冊
Spring Boot Zuul代理服務器和路由
Spring Boot雲配置服務器
Spring Boot雲配置客戶端
Spring Boot Actuator
Spring Boot管理服務器
Spring Boot管理客戶端
Spring Boot啓用Swagger2
Spring Boot創建Docker鏡像
Spring Boot跟蹤微服務日誌
Spring Boot Flyway數據庫
Spring Boot發送電子郵件
Spring Boot Hystrix
Spring Boot Web Socket
Spring Boot批量服務
Spring Boot Apache Kafka
Spring Boot單元測試用例
Spring Boot Rest控制器單元測試
Spring Boot數據庫源(連接數據庫)
Spring Boot保護Web應用程序

Spring Boot @ConfigurationProperties實例

Spring Boot [@ConfigurationProperties](https://github.com/ConfigurationProperties "@ConfigurationProperties")是讓開發人員比較容易地將整個文件映射成一個對象。

簡單屬性文件

通常,我們使用[@Value](https://github.com/Value "@Value")註釋來逐個注入.properties值,這對於小而簡單的結構.properties文件很有用。

文件:global.properties

[email protected]
thread-pool=12

@Value 示例
文件:GlobalProperties.java

@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {

    @Value("${thread-pool}")
    private int threadPool;

    @Value("${email}")
    private String email;

    //getters and setters

}

@ConfigurationProperties實例

文件:GlobalProperties.java

import org.springframework.boot.context.properties.ConfigurationProperties;

@Component
@PropertySource("classpath:global.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters

}

2.複雜屬性文件

2.1. 查看複雜的結構.properties文件,如何通過[@Value](https://github.com/Value "@Value")註釋映射值。

文件:application.properties

#Logging
logging.level.org.springframework.web=ERROR
logging.level.com.yiibai=DEBUG

#Global
[email protected]
thread-pool=10

#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login

app.compiler.timeout=5
app.compiler.output-folder=/temp/

app.error=/error/

或YAML中的下面配置, 文件: application.yml

logging:
  level:
    org.springframework.web: ERROR
    com.yiibai: DEBUG
email: [email protected]
thread-pool: 10
app:
  menus:
    - title: Home
      name: Home
      path: /
    - title: Login
      name: Login
      path: /login
  compiler:
    timeout: 5
    output-folder: /temp/
  error: /error/

注意:[@ConfigurationProperties](https://github.com/ConfigurationProperties "@ConfigurationProperties")支持.properties.yml文件。

下面可使用[@ConfigurationProperties](https://github.com/ConfigurationProperties "@ConfigurationProperties")來配置完成,創建一個[@ConfigurationProperties](https://github.com/ConfigurationProperties "@ConfigurationProperties") bean,如下所示:

文件: AppProperties.java -

package com.yiibai;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties("app") // prefix app, find app.* values
public class AppProperties {

    private String error;
    private List<Menu> menus = new ArrayList<>();
    private Compiler compiler = new Compiler();

    public static class Menu {
        private String name;
        private String path;
        private String title;

        //getters and setters

        @Override
        public String toString() {
            return "Menu{" +
                    "name='" + name + '\'' +
                    ", path='" + path + '\'' +
                    ", title='" + title + '\'' +
                    '}';
        }
    }

    public static class Compiler {
        private String timeout;
        private String outputFolder;

        //getters and setters

        @Override
        public String toString() {
            return "Compiler{" +
                    "timeout='" + timeout + '\'' +
                    ", outputFolder='" + outputFolder + '\'' +
                    '}';
        }

    }

    //getters and setters
}

文件:GlobalProperties.java -

package com.yiibai;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties // no prefix, find root level values.
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters
}
`

演示實例

測試以確保.properties值正確映射到對象。文件:WelcomeController.java -

package com.yiibai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class WelcomeController {

    private static final Logger logger = LoggerFactory.getLogger(WelcomeController.class);

    private AppProperties app;
    private GlobalProperties global;

    @Autowired
    public void setApp(AppProperties app) {
        this.app = app;
    }

    @Autowired
    public void setGlobal(GlobalProperties global) {
        this.global = global;
    }

    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {

        String appProperties = app.toString();
        String globalProperties = global.toString();

        logger.debug("Welcome {}, {}", app, global);

        model.put("message", appProperties + globalProperties);
        return "welcome";
    }

}

文件:SpringBootWebApplication.java -

package com.yiibai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}

使用Maven命令mvn spring-boot:run啓動Spring Boot,運行成功後訪問默認/控制器,查看控制檯輸出:

Welcome
    AppProperties{error='/error/',
        menus=[
            Menu{name='Home', path='/', title='Home'},
            Menu{name='Login', path='/login', title='Login'}
        ],
        compiler=Compiler{timeout='5', outputFolder='/temp/'}},

    GlobalProperties{threadPool=10, email='[email protected]'}

@ConfigurationProperties驗證

讓這個[@ConfigurationProperties](https://github.com/ConfigurationProperties "@ConfigurationProperties")支持JSR-303 bean驗證 - javax.validation

文件:GlobalProperties.java -

package com.yiibai;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@Component
@ConfigurationProperties
public class GlobalProperties {

    @Max(5)
    @Min(0)
    private int threadPool;

    @NotEmpty
    private String email;

    //getters and setters
}

嘗試再次使用Maven命令mvn spring-boot:run啓動Spring Boot,並查看控制檯:

Spring

本項目名稱爲: spring-boot-properties, 請找到下載Spring Boot代碼下載目錄,並下載。