demo.properties
配置文件
main
|_ java
|_ resources
|_ property
|_ demo.properties
demo.desc=spring boot property config of properties file
demo.babbys[0].name=Tom
demo.babbys[0].age=2
demo.babbys[0].address=苏州
demo.babbys[1].name=Lily
demo.babbys[1].age=5
demo.babbys[1].address=杭州
实体对象
import lombok.Data;
@Data
public class Babby {
private String name;
private Integer age;
private String address;
}
配置
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.List;
@Data
@Configuration
@PropertySource("classpath:property/demo.properties")
@ConfigurationProperties(prefix = "demo")
public class Demo {
private String desc;
private List<Babby> babbys;
}
使用
@Autowired
private Demo demo;
demo.json
配置文件
main
|_ java
|_ resources
|_ property
|_ demo.json
{
"desc": "spring boot property config of json file",
"babbys": [{
"name": "Tom",
"age": 2,
"address": "苏州"
},{
"name": "Lily",
"age": 5,
"address": "杭州"
}]
}
实体对象
import lombok.Data;
@Data
public class Demo {
private String desc;
private List<Babby> babbys;
}
import lombok.Data;
@Data
public class Babby {
private String name;
private Integer age;
private String address;
}
配置
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
@Configuration
public class JsonFileConfig {
@Bean
public Demo demo() throws IOException {
Resource resource = new ClassPathResource("properties/demo.json");
InputStream inputStream = resource.getInputStream();
return new ObjectMapper().readValue(inputStream, Demo.class);
}
}
使用
@Autowired
private Demo demo;