SpringBoot項目中,獲取配置文件信息


1.在配置文件中設置信息,格式如下

wechat:
  mpAppId: wxdf2b09f280e6e6e2
  mpAppSecret: f924b2e9f140ac98f9cb5317a8951c71

如果是多級目錄,則

project:
  url:
    sell: http://localhost:8080

2.獲取配置文件信息(三種方法)

2.1@ConfigurationProperties

package com.xiong.sell.config;

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

@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

    private String mpAppId;

    private String mpAppSecret;
}

2.2@Value

package com.xiong.sell.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
@Data
//@ConfigurationProperties(prefix = "project.url")
public class ProjectUrlConfig {
    
    @Value("${project.url.sell}")
    private String sell;
}

單元測試結果

2.3org.springframework.core.env.Environment;

package com.xiong.sell.config;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class ConfigTest {

    @Autowired
    private Environment environment;

    @Test
    public void test2(){
        String sell = environment.getProperty("project.url.sell");
        log.info("project.url.sell = {}",sell);
    }
}

 

單元測試結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM