Spring boot(三) 配置檔案

2021-08-04 05:00:12 字數 1781 閱讀 3304

第一種,定義引用的屬性特別少時,在屬性欄位上直接引用

實現方式:

com.anshu.name="暗鼠"
引用自定義配置檔案如下
import org.springframework.beans.factory.annotation.value;

import org.springframework.web.bind.annotation.restcontroller;

@restcontroller

public class test ")

private string name;

@value("$")

private string speak;

return name+speak;

} public string getname()

public void setname(string name)

public string getspeak()

public void setspeak(string speak)

}然後根據測試類中指定的訪問路徑進行訪問;

二,當乙個類中屬性字段特別多時,spring boot官方提供了乙個繫結乙個物件bean,這裡建立了乙個user bean,但是在bean的頂部需要使用註解@configurationproperties(prefix = 「com.anshu」)來指明使用哪個

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

@configurationproperties(prefix="com.anshu")

public class user

最後在啟動類的頂部使用註解@enableconfigurationproperties()來指明要載入那個類,如:

@enableconfigurationproperties()

public static void main(string args)

}測試類中使用如下:

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.web.bind.annotation.restcontroller;

@restcontroller

public class test

} 三,使用自定義的配置檔案

在src/main/resource資料夾下定義自定義的配置檔案,如test.properties檔案,配置檔案內容如下:

com.anshu.name="暗鼠"

com.anshu.speak="歡迎您"

指定bean檔案的引用如下:

@configuration

@configurationproperties(prefix="com.anshu")

@propertysource("classpath:test.properties")

public class user {

測試類的註解配置不變

注意:不管是直接在屬性上使用註解配置屬性值,還是使用bean的方式進行繫結物件進行使用屬性值,都要注意配置檔案中的屬性名稱都要和屬性或者bean中的屬性值一致;

例;配置檔案中的屬性設定為:com.anshu.name="暗鼠",在bean中定義的屬性也要為name,否則自定義屬性值無法注入指定屬性中

Spring Boot筆記三 配置檔案

配置檔案這裡需要講的東西很多,所以我寫在了這裡,但是這個是和上篇文章銜接的,所以看這篇文章,先看上篇文章筆記二 配置檔案裡面不能都寫我們的類的配置吧,這樣那麼多類太雜了,所以我們寫乙個person.properties person.name vae person.age 32person.boss...

Spring Boot配置檔案

方式 示例 檔案路徑 classpath或者classpath的 config目錄下 檔案內容 全域性通用配置 方式 通過environment獲取 示例 system.out println ctx.getenvironment getproperty env 方式一 configurationp...

springboot配置檔案

配置檔案的作用 修改springboot自動配置的預設值 yaml yaml ain t markup language yaml a markup language 是乙個標記語言 yaml isn t markup language 不是乙個標記語言 標記語言 以前的配置檔案大都是xml檔案,y...