欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java讀取配置文件自定義字段(yml、properties)

 更新時(shí)間:2023年07月09日 11:02:27   作者:要成為大神的小菜鳥(niǎo)Simon  
本文主要介紹了java讀取配置文件自定義字段(yml、properties),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

一、概述

在springboot項(xiàng)目配置文件中設(shè)置自定義字段,項(xiàng)目代碼按需讀取,想換重要參數(shù)時(shí)直接更改配置文件即可,這篇文章說(shuō)一說(shuō)配置文件自定義字段的方法。

二、實(shí)現(xiàn)方法

方法1 @Value

使用org.springframework.beans.factory.annotation包下的@Value注解讀取yml文件里面的字段,代碼如下:

yml文件

server:
  port: 8080
#自定義參數(shù)字段
student:
  name: Simon
  age: 23
  sex: male
  height: 185
 

讀取

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Value("${student.name}")
    private String name;
    @Value("${student.age}")
    private String age;
    @Value("${student.sex}")
    private String sex;
    @Value("${student.height}")
    private String height;
    @RequestMapping("/1")
    public Object test(){
        log.info("我叫"+name+",性別是:"+sex+",今年"+age+"歲,我還是個(gè)"+height+"cm大高個(gè)的帥小伙!");
        return "我叫"+name+",性別是:"+sex+",今年"+age+"歲,我還是個(gè)"+height+"cm大高個(gè)的帥小伙!";
    }
}

測(cè)試結(jié)果

方法2:Environment

與@value類似,注入Environment通過(guò)配置參數(shù)的前綴拿到任何配置文件里配置參數(shù)的值,優(yōu)點(diǎn)是隨時(shí)隨地,便捷,但是配置參數(shù)數(shù)量多的時(shí)候,會(huì)造成代碼冗余。

/**
 * @ClassName TestController
 * @Author
 * @Date 2023/2/28 0028 16:52
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private Environment environmentConfig;
    @PostMapping("/environment")
    public String testEnvironment(){
        String number = environmentConfig.getProperty("school.role.teacher.number");
        String age = environmentConfig.getProperty("student.age");
        System.out.println("number = " + number);
        System.out.println("age = " + age);
        return null;
    }
}

方法3:@PropertySource()、@ConfigurationProperties()

組合使用@PropertySource()、@ConfigurationProperties()兩個(gè)注解對(duì)springboot項(xiàng)目的properties配置文件的的讀取。

properties文件

student.name=simon
student.age=23
student.sex=male
student.height= 185
student.self-assessment=handsome

?。?!注意:這里與方法一yml文件采取@Value的方式讀取不同,讀取properties文件需要建一個(gè)讀取類(Studentconfig),將properties文件中想讀取得字段都注入進(jìn)去作為該類的屬性,再將Student通過(guò)@Configuration注解將其當(dāng)作Bean交給容器管理,需要用的時(shí)候?qū)tudent整個(gè)類注入,在調(diào)用get方法得到其屬性(即配置文件中的自定義字段)

StudentConfig類

@Configuration
@PropertySource("classpath:application.properties")//讀取配置文件
@ConfigurationProperties(prefix="student")//讀取節(jié)點(diǎn)
@Data
public class StudentConfig {
    private String name;
    private String sex;
    private int age;
    private int height;
    private String selfAssessment;
}

細(xì)節(jié)注意

Configuration注解的prefix有書(shū)寫(xiě)規(guī)范,據(jù)我本人經(jīng)驗(yàn)總結(jié)

  • 不可用大寫(xiě)字母
  • 不可寫(xiě)下劃線,兩個(gè)單詞需隔開(kāi)的話使用橫線
  • 不能使用數(shù)字(有博主說(shuō)可以用數(shù)字我自己試了下是不可以的,希望大家避坑)

讀?。▽tudentConfig整個(gè)類注入,再使用get方法調(diào)用)

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private StudentConfig student;
    @RequestMapping("/properties")
    public Object test2(){
        return "我叫"+student.getName()+"" +
                ",性別是:"+student.getSex()+
                ",今年"+student.getAge()+
                "歲,我還是個(gè)"+student.getHeight()+"cm大高個(gè)的帥小伙!" +
                "我對(duì)自己的評(píng)價(jià)是"+student.getSelfAssessment();
    }

得到結(jié)果

三、使用@value注解讀取yml失效的場(chǎng)景及解決辦法

springboot項(xiàng)目中常用到@value這個(gè)注解來(lái)獲取yml配置文件中的值。但是實(shí)際開(kāi)發(fā)中我們常常會(huì)忽略的的幾個(gè)導(dǎo)致它失效的原因

1.@value("${pdf.saveUrl}")當(dāng)中的路徑問(wèn)題。這也是大家所熟知的。

2.@value修飾的變量是final、static關(guān)鍵字。(這個(gè)是我們?nèi)粘?xiě)代碼中常常遇到的,也是我親身經(jīng)歷的問(wèn)題。)

3.構(gòu)造方法調(diào)用該注解修飾的字段也會(huì)失效,大家不妨嘗試一下。

4.實(shí)體類沒(méi)有@Component或這@Service或者別的能注入類的注解。也會(huì)失效。

5.采用new class來(lái)創(chuàng)建對(duì)象,調(diào)用@value修飾的字段,也同樣會(huì)失效,實(shí)際開(kāi)發(fā)中我們還是要用spring的ioc容器來(lái)創(chuàng)建該對(duì)象,@Autowired,@Resource或者構(gòu)造器的方式(這個(gè)是千萬(wàn)不能范的錯(cuò)誤寫(xiě)法)

四、嵌套讀取properties文件的方法(讀取類繼承HashMap類)

在項(xiàng)目中有時(shí)候需要接入許多不同的企業(yè),每個(gè)企業(yè)需要不同的配置參數(shù),將不同的配置參數(shù)寫(xiě)到配置文件,通過(guò)企業(yè)傳遞來(lái)的值取得不同的配置參數(shù)。

這里以學(xué)校的老師和學(xué)生為例,在不同角色和不同科目下得到的參數(shù)信息

配置文件

#老師
##人數(shù)
school.role.teacher.number=50
##老師著裝
school.role.teacher.wearing=suit
##職責(zé)
school.role.teacher.job=teach
##科目
###數(shù)學(xué)老師的stereotype
####性格
school.role.teacher.subject.math.character=serious
####性別
school.role.teacher.subject.math.sex=male
####年齡
school.role.teacher.subject.math.age=old
###英語(yǔ)老師的imagination
####性格
school.role.teacher.subject.english.character= optimistic
####性別
school.role.teacher.subject.english.sex=female
####年齡
school.role.teacher.subject.english.age=young
#學(xué)生
#數(shù)量
school.role.student.number=1000
#學(xué)生著裝
school.role.student.wearing=uniform
#任務(wù)
school.role.student.job=study
##科目
###數(shù)學(xué)課上表現(xiàn)
school.role.student.subject.math.performance=cautious
###英語(yǔ)課上表現(xiàn)
school.role.student.subject.english.performance=happy

配置類

package com.example.test.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.HashMap;
/**
 * @ClassName TestConfig
 * @Author
 * @Date 2023/2/28 0028 15:26
 */
@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "school.role")
public class TestConfig extends HashMap<String,TestConfigItem> {
}

角色層

package com.example.test.config;
import lombok.Data;
/**
 * @ClassName TestConfigItem
 * @Author
 * @Date 2023/2/28 0028 15:27
 */
@Data
public class TestConfigItem {
    /**
     * 數(shù)量
     */
    private int number;
    /**
     * 穿著
     */
    private String wearing;
    /**
     * 職責(zé)
     */
    private String job;
    /**
     * 科目
     */
    private InnerConfig subject;
}
package com.example.test.config;
import lombok.Data;
import java.util.HashMap;
/**
 * @ClassName InnerConfig
 * @Author
 * @Date 2023/2/28 0028 15:48
 */
@Data
public class InnerConfig extends HashMap<String,InnerConfigItem> {
}

科目層

package com.example.test.config;
import lombok.Data;
/**
 * @ClassName InnerConfigItem
 * @Author
 * @Date 2023/2/28 0028 15:49
 */
@Data
public class InnerConfigItem {
    /**
     * 性格
     */
    private String character;
    /**
     *性別
     */
    private String sex;
    /**
     *年齡
     */
    private String age;
    /**
     *學(xué)生表現(xiàn)
     */
    private String performance;
}

讀取

package com.example.test.controller;
import com.example.test.config.InnerConfigItem;
import com.example.test.config.TestConfig;
import com.example.test.config.TestConfigItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * @ClassName TestController
 * @Author
 * @Date 2023/2/28 0028 16:52
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private TestConfig config;
    @GetMapping("/properties/{role}/{subject}")
    public String testProperties(@PathVariable String role,@PathVariable String subject){
        String result= null;
        TestConfigItem testConfigItem = config.get(role);
        int number = testConfigItem.getNumber();
        String wearing = testConfigItem.getWearing();
        String job = testConfigItem.getJob();
        InnerConfigItem innerConfigItem = testConfigItem.getSubject().get(subject);
        String age = innerConfigItem.getAge();
        String character = innerConfigItem.getCharacter();
        String sex = innerConfigItem.getSex();
        if ("student".equals(role)){
            String performance = innerConfigItem.getPerformance();
             result = "目前角色是"+role+",人數(shù)為"+number+",職責(zé)是"+job+",穿著"+wearing+"。在"+subject+"課上的表現(xiàn)是"+performance+"。";
            return result;
        }
         result = "目前角色是"+role+",人數(shù)為"+number+",職責(zé)是"+job+",穿著"+wearing+"。" +
                 "在"+subject+"課上是"+character+"的,年齡是"+age+",性別是"+sex+"。";
        return result;
    }
}

結(jié)果

到此這篇關(guān)于java讀取配置文件自定義字段(yml、properties)的文章就介紹到這了,更多相關(guān)java讀取配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Springboot項(xiàng)目中內(nèi)嵌sqlite數(shù)據(jù)庫(kù)的配置流程

    Springboot項(xiàng)目中內(nèi)嵌sqlite數(shù)據(jù)庫(kù)的配置流程

    這篇文章主要介紹了Springboot項(xiàng)目中內(nèi)嵌sqlite數(shù)據(jù)庫(kù)的配置流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • JAVA中重寫(xiě)(Override)與重載(Overload)的相關(guān)示例

    JAVA中重寫(xiě)(Override)與重載(Overload)的相關(guān)示例

    這篇文章主要給大家介紹了關(guān)于JAVA中重寫(xiě)(Override)與重載(Overload)的相關(guān)示例,重寫(xiě)(override)和重載(overload)是兩種不同的方法重用技術(shù),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-10-10
  • 深入淺析Spring 中的Null-Safety

    深入淺析Spring 中的Null-Safety

    Spring Framework 本身利用了上面這幾個(gè)注釋,但它們也可以運(yùn)用在任何基于Spring的Java 項(xiàng)目中,以聲明空安全api 和 空安全字段。這篇文章主要介紹了Spring 中的Null-Safety相關(guān)知識(shí) ,需要的朋友可以參考下
    2019-06-06
  • SpringBoot啟動(dòng)流程入口參數(shù)創(chuàng)建對(duì)象源碼分析

    SpringBoot啟動(dòng)流程入口參數(shù)創(chuàng)建對(duì)象源碼分析

    這篇文章主要為大家介紹了SpringBoot啟動(dòng)流程入口參數(shù)研究及創(chuàng)建對(duì)象源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • 詳解Java對(duì)象轉(zhuǎn)換神器MapStruct庫(kù)的使用

    詳解Java對(duì)象轉(zhuǎn)換神器MapStruct庫(kù)的使用

    在我們?nèi)粘i_(kāi)發(fā)的程序中,為了各層之間解耦,一般會(huì)定義不同的對(duì)象用來(lái)在不同層之間傳遞數(shù)據(jù)。當(dāng)在不同層之間傳輸數(shù)據(jù)時(shí),不可避免地經(jīng)常需要將這些對(duì)象進(jìn)行相互轉(zhuǎn)換。今天給大家介紹一個(gè)對(duì)象轉(zhuǎn)換工具M(jìn)apStruct,代碼簡(jiǎn)潔安全、性能高,強(qiáng)烈推薦
    2022-09-09
  • Java重寫(xiě)(Override)與重載(Overload)區(qū)別原理解析

    Java重寫(xiě)(Override)與重載(Overload)區(qū)別原理解析

    這篇文章主要介紹了Java重寫(xiě)(Override)與重載(Overload)區(qū)別原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Quartz中的Job與JobDetail解析

    Quartz中的Job與JobDetail解析

    這篇文章主要介紹了Quartz中的Job與JobDetail解析,你定義了一個(gè)實(shí)現(xiàn)Job接口的類,這個(gè)類僅僅表明該job需要完成什么類型的任務(wù),除此之外,Quartz還需要知道該Job實(shí)例所包含的屬性;這將由JobDetail類來(lái)完成,需要的朋友可以參考下
    2023-11-11
  • Java中的StackOverflowError錯(cuò)誤問(wèn)題及解決方法

    Java中的StackOverflowError錯(cuò)誤問(wèn)題及解決方法

    這篇文章主要介紹了Java中的StackOverflowError錯(cuò)誤,在本文中,我們仔細(xì)研究了StackOverflower錯(cuò)誤,包括Java代碼如何導(dǎo)致它,以及我們?nèi)绾卧\斷和修復(fù)它,需要的朋友可以參考下
    2022-07-07
  • spring中@Transactional?注解失效的原因及解決辦法

    spring中@Transactional?注解失效的原因及解決辦法

    面試中經(jīng)常會(huì)被問(wèn)到事務(wù)失效的場(chǎng)景有哪些,本文主要介紹了spring中@Transactional?注解失效的原因及解決辦法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-06-06
  • LibrarySystem圖書(shū)管理系統(tǒng)(二)

    LibrarySystem圖書(shū)管理系統(tǒng)(二)

    這篇文章主要為大家詳細(xì)介紹了LibrarySystem圖書(shū)管理系統(tǒng)開(kāi)發(fā)第二篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05

最新評(píng)論