springboot项目读取自定义porperties文件
1.1.定义简单.properties文件
datasource.dataSources[0].id=1 datasource.dataSources[0].dsId=postgisA datasource.dataSources[0].type=postgis datasource.dataSources[0].driver=org.postgresql.Driver datasource.dataSources[0].url=jdbc:postgresql:// datasource.dataSources[0].user=postgres datasource.dataSources[0].pwd=****
1.2.定义实体类
import lombok.Data; @Data public class DataSource { private int id; private String dsId; private String type; private String driver; private String url; private String user; private String pwd; }
1.3.读取配置文件
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import java.util.ArrayList; @Data @Configuration @PropertySource("classpath:property/datasource.properties") @ConfigurationProperties(prefix = "datasource") public class DataSources { private ArrayList<DataSource> dataSources; }
2.1定义复杂.properties
services.servers[0].name=Test services.servers[0].dsId=postgisA services.servers[0].layers[0].name=Test services.servers[0].layers[0].type=LineString services.servers[0].layers[0].minLevel = 16 services.servers[0].layers[0].maxLevel = 18 services.servers[0].layers[1].name=Test2 services.servers[0].layers[1].type=Point services.servers[0].layers[1].minLevel = 16 services.servers[0].layers[1].maxLevel = 18
2.2定义两个实体类
import lombok.Data; @Data public class Layer { private String name; private String type; private int minLevel; private int maxLevel; }
import lombok.Data; import java.util.ArrayList; @Data public class LayerService { private int id; private String name; private String dsId; private String extent; private String cachePath; private ArrayList<Layer> layers; }
2.3读取配置
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import java.util.ArrayList; @Data @Configuration @PropertySource("classpath:property/services.properties") @ConfigurationProperties(prefix = "services") public class Services { private ArrayList<LayerService> servers; }
3.使用
直接注入
@Autowired
DataSources dataSources;
@Autowired
Services services;