您现在的位置是:网站首页>JavaJava

SpringBoot四种读取properties配置文件的方式yml文件通用

左鹏03-31 16:31:45Java1,568人已围观

简介使用如下为 .yml 后缀的默认 application.yml 文件,.properties 格式文件也是一样的 #application.yml yipengke: domain: https://www.zuopeng.gd.cn login-url: https://login.zuopeng.gd.cn/oauth 一、使用`@ConfigurationProperties`注解将配置文件属性注入到自定义配置对象类中 1.首先定义配置对象 import o

使用如下为 .yml 后缀的默认 application.yml 文件,.properties 格式文件也是一样的

#application.yml

yipengke:
  domain: https://www.zuopeng.gd.cn
  login-url: https://login.zuopeng.gd.cn/oauth

一、使用`@ConfigurationProperties`注解将配置文件属性注入到自定义配置对象类中

1.首先定义配置对象

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

@Component
@ConfigurationProperties(prefix = "yipengke")
public class ConfigTest {
    private String domain;
    private String loginUrl;


    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }
}

2.运行后得到结果

import com.xxx.ConfigTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("test")
public class Test {

    @Autowired
    ConfigTest configTest;

    @GetMapping("test")
    public ConfigTest test(){
        return configTest;
    }
}

二、使用`@Value("${propertyName}")`注解

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("test")
public class Test {
    
    @Value("${yipengke.domain}")
    String domain;
    @Value("${yipengke.login-url}")
    String loginUrl;
    
    @GetMapping("test2")
    public String test2(){
        JSONObject data = new JSONObject();
        data.put("domain",this.domain);
        data.put("loginUrl",this.loginUrl);
        return data.toJSONString();
    }
}

三、使用Environment,在任何想要用的地方直接获取配置的值

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test")
public class Test {

    @Autowired
    Environment env;

    @GetMapping("test3")
    public String test3(){
        JSONObject data = new JSONObject();
        data.put("domain",env.getProperty("yipengke.domain"));
        data.put("loginUrl",env.getProperty("yipengke.login-url"));
        return data.toJSONString();
    }
}

四、通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式(比较前三种方式,更加复杂), 不适用于 .yml 配置文件的方式

1、编写加载配置文件的类

import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesListenerConfig {
    public static Map<String,String> propertiesMap = new HashMap<>();

    private static void processProperties(Properties properties){
        propertiesMap = new HashMap<String,String>();
        for(Object key :properties.keySet()){
            String keyStr = key.toString();
            try{
                propertiesMap.put(keyStr,new String(properties.getProperty(keyStr).getBytes(StandardCharsets.UTF_8)));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void  loadAllProperties(String propertyFileName){
        try{
            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
            processProperties(properties);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static String getProperty(String name){
        return propertiesMap.get(name).toString();
    }

    public static Map<String,String> getAllProperty(){
        return propertiesMap;
    }
}

2、编写配置文件监听器,用来加载自定义配置文件 ,实现ApplicationListener<ApplicationStartedEvent>

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;

public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {

    private String propertyFileName;

    public PropertiesListener(String propertyFileName){
        this.propertyFileName = propertyFileName;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        //引用具体的加载类
        PropertiesListenerConfig.loadAllProperties(propertyFileName);
    }
}

3、修改启动类,注册监听器

import com.xxxxx.PropertiesListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class YipengkeApplication {

    public static void main(String[] args) {
//        SpringApplication.run(YipengkeApplication.class, args);
        SpringApplication application = new SpringApplication(YipengkeApplication.class);
        application.addListeners(new PropertiesListener("application.properties"));
        application.run(args);
    }

}

4、编写测试类,运行结果如下

import com.alibaba.fastjson.JSONObject;
import com.xxxxx.PropertiesListenerConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test")
public class Test {


    @GetMapping("test4")
    public String test4(){
        JSONObject data = new JSONObject();
        data.put("domain", PropertiesListenerConfig.getProperty("yipengke.domain"));
        data.put("loginUrl",PropertiesListenerConfig.getProperty("yipengke.login-url"));
        return data.toJSONString();
    }
}

 

文章评论

    请先说点什么
    热门评论
    0人参与,0条评论
    正在载入评论列表...

    站点信息

    • 建站时间:2018-09-18
    • 网站程序:Spring Boot
    • 主题模板:《今夕何夕》
    • 文章统计:104条
    • 微信公众号:扫描二维码,关注我们
    登陆您的账户