当前位置: 代码网 > it编程>编程语言>Java > SpringBoot如何读取application.properties配置文件

SpringBoot如何读取application.properties配置文件

2024年05月28日 Java 我要评论
方案1使用propertiesloaderutilsimport java.util.properties;import org.springframework.core.io.resource;im

方案1

使用propertiesloaderutils

import java.util.properties;
import org.springframework.core.io.resource;
import org.springframework.core.io.classpathresource;
import org.springframework.core.io.support.propertiesloaderutils;
 
public static properties readpropertiesfile(string filename) {
    try {
        resource resource = new classpathresource(filename);
        properties props = propertiesloaderutils.loadproperties(resource);
        return props;
    } catch (exception e) {
        system.out.println("读取配置文件:" + filename + "异常,读取失败");
        e.printstacktrace();
    }
    return null;
}
properties properties = readpropertiesfile("application.properties");
system.out.println(properties.getproperty("spring.rabbitmq.host"));

方案2

使用environment

import org.springframework.core.env.environment;
 
@autowired
private environment environment;
 
system.out.println(environment.getproperty("spring.rabbitmq.host"));

方案3

使用@value

import org.springframework.beans.factory.annotation.value;
 
@value("${spring.rabbitmq.host}")
private string rabbitmqhost;
 
system.out.println(rabbitmqhost);

方案4

使用@configurationproperties

属性类

import lombok.getter;
import lombok.setter;
import org.springframework.boot.context.properties.configurationproperties;
 
@getter
@setter
@configurationproperties(prefix = "spring.rabbitmq")
public class testproperties {
    private string host;
    private string port;
    private string username;
    private string password;
}

注册属性配置类

import org.springframework.boot.springbootconfiguration;
import org.springframework.boot.context.properties.enableconfigurationproperties;
 
@enableconfigurationproperties(testproperties.class)
@springbootconfiguration
public class testconfiguration {
}

使用配置类

@autowired
private testproperties testproperties;
 
system.out.println(testproperties.gethost());

static静态方法读取配置

@component
public class userutil {
    // 使用@value注解读取配置
    @value("${user.name}")
    private string name;
 
    // 设置静态成员变量用来接收@value注入的值
    private static string username;
 
    // 使用@postconstruct注解用于静态变量赋值
    @postconstruct
    public void getusername() {
        username = this.name;
    }
 
    // 测试方法静态变量是否被赋值
    public static string test() {
        return username;
    }
}

调用示例: 

string name = userutil.test();

使用 @component 属性注解说明是需要在启动类 application 启动的时候加载。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com