Spring系列之——springboot解析resources.application.properties文件

来源:https://www.cnblogs.com/guobm/archive/2019/02/21/10415795.html
-Advertisement-
Play Games

本文通過講解如何解析application.properties屬性,介紹了幾個註解的運用@Value @ConfigurationProperties @EnableConfigurationProperties @Autowired @ConditionalOnProperty ...


  摘要:本文通過講解如何解析application.properties屬性,介紹了幾個註解的運用@Value @ConfigurationProperties @EnableConfigurationProperties @Autowired @ConditionalOnProperty

 

1 準備

1.1 搭建springboot

1.2 寫一個controller類

package com.gbm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        return "我愛北京天安門!";
    }
}
View Code

2 幾種獲取屬性值方式

  配置application.properties

value.local.province=Zhejiang
value.local.city=Hangzhou

complex.other.province=Jiangsu
complex.other.city=Suzhou
complex.other.flag=false
View Code

2.1 使用註解@Value("${xxx}")獲取指定屬性值

  2.1.1 在controller類中獲取屬性值

package com.gbm.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @Value("${value.local.province}")
    private String province;

    @Value("${value.local.city}")
    private String city;

    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.city);
        sb.append(",");
        sb.append(this.province);
        sb.append(" ");
        return sb.toString();
    }
}
View Code

  2.1.2 任何瀏覽器上運行 http://localhost:8080/index,結果如下  

  

2.2 使用註解@ConfigurationProperties(prefix = "xxx")獲得首碼相同的一組屬性,並轉換成bean對象

  2.2.1 寫一個實體類

package com.gbm.models;

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

/**
 * Created by Administrator on 2019/2/21.
 */
@Component
@ConfigurationProperties(prefix = "complex.other")
public class Complex {
    private String province;
    private String city;
    private Boolean flag;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Boolean getFlag() {
        return flag;
    }

    public void setFlag(Boolean flag) {
        this.flag = flag;
    }

    @Override
    public String toString() {
        return "Complex{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", flag=" + flag +
                '}';
    }
}
View Code

  2.2.2 在controller類中獲取屬性值

package com.gbm.controller;

import com.gbm.models.Complex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @Autowired
    private Complex complex;

    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        return complex.toString();
    }
}
View Code

  2.2.3 在SpringBootApplication中使Configuration生效

package com.gbm.myspingboot;

import com.gbm.models.Complex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

@SpringBootApplication
@ComponentScans({@ComponentScan("com.gbm.controller"), @ComponentScan("com.gbm.models")})
@EnableConfigurationProperties(Complex.class)
@ConditionalOnProperty(value = "complex.other.town", matchIfMissing = true)
public class MyspingbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyspingbootApplication.class, args);
    }
}
View Code

  2.2.4 任何瀏覽器上運行 http://localhost:8080/index,結果如下 

  

3 總結

  關於解析application.properties文件,最重要的是對註解的使用,本文主要涉及到如下幾個註解的運用

  @Value("${xxx}")——獲取指定屬性值

  @ConfigurationProperties(prefix = "xxx")——獲得首碼相同的一組屬性,並轉換成bean對象

  @EnableConfigurationProperties(xxx.class)——使Configuration生效,並從IOC容器中獲取bean

  @Autowired——自動註入set和get方法

  @ConditionalOnProperty(value = "complex.other.town", matchIfMissing = true)——缺少該property時是否可以載入,如果是true,沒有該property也會正常載入;如果是false則會拋出異常。例如

package com.gbm.myspingboot;

import com.gbm.models.Complex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

@SpringBootApplication
@ComponentScans({@ComponentScan("com.gbm.controller"), @ComponentScan("com.gbm.models")})
@EnableConfigurationProperties(Complex.class)
@ConditionalOnProperty(value = "complex.other.town", matchIfMissing = false)
public class MyspingbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyspingbootApplication.class, args);
    }
}
matchIfMissing=false代碼
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-02-21 23:30:56.532 ERROR 3152 --- [           main] o.s.boot.SpringApplication               : Application run failed

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 簡介 處理併發問題的重點不在於你的設計是怎樣的,而在於你要評估你的併發,併在併發範圍內處理。你預估你的併發是多少,然後測試r+m是否支持。緩存的目的是為了應對普通對象資料庫的讀寫限制,依托與nosql的優勢進行高速讀寫。 redis本身也有併發瓶頸。所以你要把讀寫和併發區分開來處理。只讀業務是不是可 ...
  • [TOC] JSON Web Token(縮寫 JWT)是目前最流行的跨域認證解決方案,本文介紹它的原理和用法。 一、跨域認證的問題 互聯網服務離不開用戶認證。一般流程是下麵這樣。 1. 用戶向伺服器發送用戶名和密碼。 2. 伺服器驗證通過後,在當前對話(session)裡面保存相關數據,比如用戶角 ...
  • Python環境的安裝 安裝Python: windows: 1、下載安裝包 https://www.python.org/downloads/ 2、安裝 預設安裝路徑:C:\python27 3、配置環境變數 【右鍵電腦】--》【屬性】--》【高級系統設置】--》【高級】--》【環境變數】--》 ...
  • 前言 開心一刻 一名劫匪慌忙中竄上了一輛車的後座,上車後發現主駕和副駕的一男一女疑惑地回頭看著他,他立即拔出槍威脅到:“趕快開車,甩掉後面的警車,否則老子一槍崩了你!”,於是副駕上的男人轉過臉對那女的說:“大姐,別慌,聽我口令把剛纔的動作再練習一遍,掛一檔,輕鬆離合,輕踩油門,走...走,哎 走.. ...
  • 題意 "題目鏈接" 有$n$個位置,每次你需要以$1 \sim n 1$的一個排列的順序去染每一個顏色,第$i$個數可以把$i$和$i+1$位置染成黑色。一個排列的價值為最早把所有位置都染成黑色的次數。問所有排列的分數之和 Sol 神仙題Orz 不難想到我們可以枚舉染色的次數$i \in [\lce ...
  • 《數據結構》這門課程的安排,就要開始各種演算法和數構的燒腦學習了,從最簡單的應用題型入手吧。 本題要求你寫個程式把給定的符號列印成沙漏的形狀。例如給定17個“*”,要求按下列格式列印 所謂“沙漏形狀”,是指每行輸出奇數個符號;各行符號中心對齊;相鄰兩行符號數差2;符號數先從大到小順序遞減到1,再從小到 ...
  • 在做關於NIO TCP編程小案例時遇到無法監聽write的問題,沒想到只是我的if語句的位置放錯了位置,哎,看了半天沒看出來 貼下課堂筆記: 在Java中使用NIO進行網路TCP套接字編程主要以下幾個類: ServerSocketChannel: 服務端套接字通道,主要監聽接收客戶端請求 Selec ...
  • wxPython框架雖然成熟穩定,但是相對最近更火的PyQt框架來說,還是顯得古老了一些,控制項風格不符合現代審美觀,因此痞子衡決定學習一下PyQt的用法,感受下PyQt做出來的界面效果到底如何。根據wxPython學習經驗,當然首先要從PyQt的可視化GUI構建工具Qt Designer開始下手,因... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...