首页 > 编程语言 > 详细

SpringBoot项目中,获取配置文件信息

时间:2019-01-28 19:59:43      阅读:253      评论:0      收藏:0      [点我收藏+]

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);
    }
}

 

单元测试结果

技术分享图片

 

SpringBoot项目中,获取配置文件信息

原文:https://www.cnblogs.com/xzmxddx/p/10331502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!