springboot项目获取统一前缀配置以及获取非确定名称配置
在springboot项目中,我们经常看到统一前缀的配置,我们该怎么统一获取
my.config.a.name=xiaoming
my.config.a.age=18
my.config.a.address=guangdongmy.config.b.name=xiaomli
my.config.b.age=20
my.config.b.address=shandong
方式一:使用对应的配置类并结合注解:@configurationproperties(prefix = “xxx.xxx”)
配置文件:
my.config.name=xiaoming my.config.age=18 my.config.address=guangdong
对应的配置类:myproperties
import lombok.getter;
import lombok.setter;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
/**
* @author gooluke
*/
@component
@configurationproperties(prefix = "my.config")
@getter
@setter
public class myproperties {
private string name;
private int age;
private string address;
}获取配置类,打印属性:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
@requestmapping("/test")
public class testcontroller {
@autowired
private myproperties myproperties;
@requestmapping("/show")
public void show() {
system.out.println("myproperties.getname() = " + myproperties.getname());
system.out.println("myproperties.getage() = " + myproperties.getage());
system.out.println("myproperties.getaddress() = " + myproperties.getaddress());
}
}打印结果:

方式二:获取统一前缀,而后面非确定字段名的配置
配置文件:
my.config.a.name=xiaoming my.config.a.age=18 my.config.a.address=guangdong my.config.b.name=xiaomli my.config.b.age=20 my.config.b.address=shandong
对应的配置类:
import lombok.getter;
import lombok.setter;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
import java.util.map;
/**
* @author gooluke
*/
@component
@configurationproperties(prefix = "my")
@getter
@setter
public class myproperties2 {
//这里的config得对应上my.config.xx里的config
private map<string, userinfoconfig> config;
@setter
@getter
public static class userinfoconfig {
private string name;
private integer age;
private string address;
}
}获取配置类,打印属性:
@autowired
private myproperties2 myproperties2;
@requestmapping("/show2")
public void show2() {
map<string, myproperties2.userinfoconfig> config = myproperties2.getconfig();
config.foreach((user, userinfoconfig) -> {
system.out.println("user = " + user);
system.out.println("userinfoconfig.getname() = " + userinfoconfig.getname());
system.out.println("userinfoconfig.getage() = " + userinfoconfig.getage());
system.out.println("userinfoconfig.getaddress() = " + userinfoconfig.getaddress());
});
}打印结果:

到此这篇关于springboot项目获取统一前缀配置以及获取非确定名称配置的文章就介绍到这了,更多相关springboot获取统一前缀配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论