Spring Boot读取yml或者properties配置数据

1 使用@Value注解

一般用于 非static

@Value 注解即可获取。

增加注解@RefreshScope,可以使得配置实时生效(实践使用nacos做配置中心的时候)

@Configuration
@RefreshScope
public class InquiryConfig {

    @Value("${prepared.template.filepath}")
    private String templateFilePath;
}    

static也可以使用@Value,使用setter方法.

    public static String tempFileName;

    private static String templateFilePath;

    @Value("${esign.templateFile}")
    public void setTxtResource(String templateFilePath) {
        tempFileName = templateFilePath;
    }

2使用Environment

可以获取static修饰的变量

@Autowired
private Environment env;

public static String hbase_zookeeper_quorum;

public static String hbase_zookeeper_property_clientPort;

@PostConstruct
private void init() {
    hbase_zookeeper_quorum = env.getProperty("hbase.quorum");
    hbase_zookeeper_property_clientPort = env.getProperty("hbase.clientPort");
    conf = HBaseConfiguration.create();
    System.out.println(hbase_zookeeper_quorum);
    System.out.println(".>>>>>>>>>>>>>>>>>");

    conf.set("hbase.zookeeper.quorum", hbase_zookeeper_quorum);
    conf.set("hbase.zookeeper.property.clientPort", hbase_zookeeper_property_clientPort);
    try {
        conn = ConnectionFactory.createConnection(conf);
        admin = conn.getAdmin();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 增加 Environment
  2. PostConstuct 注解方法,第一次执行
  3. env.getProperty(“hbase.quorum”) 获取具体值

3 读取文件的方式

读取config.preperties文件的所有配置

使用方式:

SysConfig.getInstance().getProperty("属性key");
// 比如
SysConfig.getInstance().getProperty("message.templateid");

代码

package com.prepared.config;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Properties;

public class SysConfig {
    private Properties props = null;// config.properties
    private static volatile SysConfig conf;

    private SysConfig() {
        props = new Properties();
        loadConfigProps();
    }

    public static SysConfig getInstance() {
        if (conf == null) {
            synchronized (SysConfig.class) {
                if (conf == null) {
                    conf = new SysConfig();
                }
            }
        }
        return conf;
    }

    public void loadConfigProps() {
        InputStream is = null;
        try {
            is = getClass().getResourceAsStream("/WEB-INF/classes/config.properties");
            if (is == null) {
                is = getClass().getResourceAsStream("/config.properties");
            }
            InputStreamReader reader = new InputStreamReader(is, "UTF-8");
            props.load(reader);
            Iterator<String> iter = props.stringPropertyNames().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                props.setProperty(key, props.getProperty(key));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getProperty(String key) {
        String tmp = props.getProperty(key);
        if (StringUtils.isNotEmpty(tmp)) {
            return tmp.trim();
        }
        return tmp;
    }

    public String getProperty(String key, String defaultValue) {
        String tmp = props.getProperty(key, defaultValue);
        if (StringUtils.isNotEmpty(tmp)) {
            return tmp.trim();
        }
        return tmp;
    }

    public int getPropertyInt(String key) {
        String tmp = props.getProperty(key);
        if (StringUtils.isNotEmpty(tmp)) {
            return Integer.parseInt(tmp.trim());
        }
        return 0;

    }

    public int getPropertyInt(String key, int defaultValue) {
        String tmp = props.getProperty(key);
        if (StringUtils.isNotEmpty(tmp)) {
            return Integer.parseInt(tmp.trim());
        }
        return defaultValue;
    }

    public long getPropertyLong(String key, long defaultValue) {
        String tmp = props.getProperty(key);
        if (StringUtils.isNotEmpty(tmp)) {
            return Integer.parseInt(tmp.trim());
        }
        return defaultValue;
    }
}

### 回答1: 在 Spring Boot读取 YAML 文件可以使用注解 `@Value` 或者 `@ConfigurationProperties`。 使用 `@Value` 注解: ```java @Value("${property.name}") private String propertyName; ``` 使用 `@ConfigurationProperties` 注解: ```java @ConfigurationProperties(prefix = "property") @Data public class Property { private String name; } ``` 在 application.yml 文件中配置相应的属性: ```yml property: name: value ``` 然后在应用程序中通过注入 Bean 的方式使用即可。 ### 回答2: Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架,它提供了许多便利的功能,其中之一是读取yml文件。 首先,我们需要在Spring Boot项目中添加YAML文件。YAML(YAML Ain't Markup Language)是一种简洁且易读的数据序列化格式,通常用于配置文件。 在src/main/resources目录下创建一个名为application.yml的文件。在该文件中,我们可以使用键值对的形式来配置各种属性。 例如,我们可以配置服务器端口号: server: port: 8080 然后,我们需要创建一个类来读取yml配置文件中的属性。可以使用@ConfigurationProperties注解将该类与yml文件中的属性进行绑定。 ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "server") public class ServerProperties { private int port; public int getPort() { return port; } public void setPort(int port) { this.port = port; } } ``` 在上述示例中,我们使用@ConfigurationProperties注解指定了yml文件中的配置项前缀为"server",然后定义了一个整型属性port,通过对应的getter和setter方法可以获取和设置该属性的值。 最后,我们可以在其他组件或Bean中使用该ServerProperties类来获取yml文件中的属性值。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyComponent { private final ServerProperties serverProperties; @Autowired public MyComponent(ServerProperties serverProperties) { this.serverProperties = serverProperties; } public void printServerPort() { int port = serverProperties.getPort(); System.out.println("Server port: " + port); } } ``` 在上述示例中,我们通过构造函数注入了ServerProperties对象,并在printServerPort方法中获取了yml文件中配置的服务器端口号,然后打印出来。 这样,我们就可以通过Spring Boot读取yml文件中的属性值了。Spring Boot会自动将yml文件中的属性与@Component注解的类进行绑定,从而方便我们使用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伍六七AI编程

你猜你给我1分我要不要

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值