方案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 启动的时候加载。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论