配置文件读取
项目根目录的config目录下person.yml, 文件夹如下
person:
name: qinjiang
age: 3
happy: false
birth: 2000/01/01
maps: {k1: v1, k2: v2}
lists:
- code
- girl
- music
dog:
name: 旺财
age: 1
device.json文件
{
"id": 23,
"name": "robot",
"state": 2,
"point": [
1,
2
]
}
单个注入: @Value
可用于json/yml文件
@Component
@PropertySource(value = {"file:./config/person.yml"},factory = YamlPropertySourceFactory.class)
//@PropertySource(value = {"file:./config/device.json"})
public class Cat {
@Value("${person.dog.name}")
// @value(${id}) // device.json文件中的字段
private String name;
@Bean
public void testValue(){
System.out.println("field name is injected through @Value:" + name);
}
}
________________________________________
field name is injected through @Value:旺财
批量注入: @ConfigurationProperties注解
yml文件
这个注解常用于yml文件, 可以通过@PropertySource注解指定配置文件的路径. 其中file:./config/person.yml表示的项目的根路径下的文件夹config下文件person,.yml, 可以发现它是按名字匹配的.
package com.wang.yml;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Person : TODO
*
* @author : Wangwenchu
* @since : 2023/1/12
*/
@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"file:./config/person.yml"},factory = YamlPropertySourceFactory.class)
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
@Data
public class Dog {
private String name;
private int age;
}
-------------------------------------
Person(name=qinjiang, age=3, happy=false, birth=Sat Jan 01 00:00:00 CST 2000,
maps={k1=v1, k2=v2}, lists=[code, girl, music], dog=Dog(name=旺财, age=1))
其中YamlPropertySourceFactory为:
package com.wang.yml;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* YamlPropertySourceFactory : TODO
*
* @author : Wangwenchu
* @since : 2023/1/13
*/
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String sourceName, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYaml(resource);
if(sourceName == null || sourceName.length() == 0){
sourceName = resource.getResource().getFilename();;
}
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYaml(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
json文件读取
导入fastjson的maven依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
常用的操作
获取单个属性
以下面的device.json为例:
{
"id": 23,
"name": "robot",
"state": 2,
"point": [
1,
2
]
}
- json path -- > File --> String --> JSONObject --> 调用getString(name)
public void getPropertyFromObject() {
String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "device.json";
File file = new File(path);
try {
String json = FileUtils.readFileToString(file);
JSONObject jsonObject = JSONObject.parseObject(json);
System.out.println("name:" + jsonObject.getString("name"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
_________________________
name:robot
json转指定对象
还是以下面的device.json文件为例:
构建pojo类Robot, 其中故意增加一个没有的字段code:
@Data
public class Robot {
private String id;
private String name;
private int state;
private String code;
private List<String> point;
}
JSON.parseObject实现转为, 注意也是按照属性名和配置文件中的相匹配(大小写忽略), 没有的字段为null, 存在的就注入
public void getObject() {
String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "device.json";
File file = new File(path);
try {
String json = FileUtils.readFileToString(file);
Robot config = JSON.parseObject(json,Robot.class);
System.out.println(config.getId());
System.out.println(config.getName());
System.out.println(config.getState());
System.out.println(config.getCode()); // null
System.out.println(config.getPoint().get(0));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
___________________
23
robot
2
null
1
json文件转为指定的对象列表
如下为goods.json文件, 想转为List
[
{
"id": 1,
"name": "robot1",
"state": 0,
"point": [
1,
2
]
},
{
"id": 2,
"name": "robot2",
"state": 1,
"point": [
3,
4
]
}
]
借助JSON.parseArray
public void getObjectArray() {
String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "goods.json";
File file = new File(path);
try {
String json = FileUtils.readFileToString(file);
List<Robot> list = JSON.parseArray(json,Robot.class);
System.out.println(list.get(0));
System.out.println(list.get(1));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
______________________________________
Robot(id=1, name=robot1, state=0, code=null, point=[1, 2])
Robot(id=2, name=robot2, state=1, code=null, point=[3, 4])
标签:springboot,配置文件,private,String,json,import,config,name From: https://www.cnblogs.com/shmilyt/p/17054555.html