目录
一、配置文件注入方式一@Value
二、配置文件注入方式二@ConfigurationProperties
三、自定义解析类,直接暴力读取yml配置文件
四、Spring配置文件的解析类Environment获取式
配置文件:
# 严格识别空格
# 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)
properties:
name1: 徐城和
# 数组/集合(Arrays/List/Set)
arrays:
srr1: 小徐,小杨
srr2: [小张,小林]
# 键值对(Map)
maps:
map1: {key1: value1,key2: value2}
注入/解析类:
package parseconfiguration;
import autowired.SubGenericityApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Set;
/**
* 配置文件注入方式一@Value
*
* 其中,该注入方式:
* -仅可注入单属性值和常规数组/集合写法,其它配置或写法需要使用方式二注入
* -属性不需要Get/Set方法支持
* -可以注入任意类型数据,自动转换注入
* -没配置或无法识别或类型无法转换,均会导致配置失败,会报错,因此需要配合default默认值使用
*
* @author Chenghe Xu
* @date 2023/2/14 10:34
*/
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test01 {
@Value("${properties.name1}")
private String name1;
@Value("${arrays.srr1}")
// private String[] srr1;
// private List srr1;
private Set srr1;
@Test
public void test1() {
System.out.println("name1 = " + name1);
System.out.print("srr1 = |");
for (String s : srr1) {
System.out.print(s + "|");
}
System.out.println();
}
}
/**
* 数组注入时会按英文逗号分割
* 字符串不会
*/
@SpringBootTest(classes = SubGenericityApplication.class)
class Test01_1 {
/**
* 在生产环境,@Value防止没配置或注入失败,直接报错,需要配合default使用
*/
@Value("${properties.name2:没配置,没默认值会直接报错}")
private String name2;
@Value("${arrays.srr2:无法识别,没默认值会直接报错}")
// private String[] srr2;
// private List srr2;
private Set srr2;
@Value("${maps.map1:类型无法转换,没默认值会直接报错}")
private String map1;
@Test
public void test1() {
System.out.println("name2 = " + name2);
System.out.print("srr2 = |");
for (String s : srr2) {
System.out.print(s + "|");
}
System.out.println();
System.out.println("map1 = " + map1);
}
}
配置文件:
# 严格识别空格
myproperties:
# 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)
name1: 徐城和
# 数组/集合(Arrays/List/Set)
srr1: 小徐,小杨
srr2: [小张,小林]
srr3:
- 小君
- 小白
# 键值对(Map)
map1: {key1: value1,key2: value2}
map2:
key3: value3
key4: value4
# 对象(Object)
pet1: {name: 旺财,age: 3}
pet2:
name: 莉莉
age: 2
注入/解析类:
package parseconfiguration;
import autowired.SubGenericityApplication;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
/**
* 配置文件注入方式二@ConfigurationProperties
*
* 其中,该注入方式:
* -需要配合启动类注解标记:@EnableConfigurationProperties({Test02.class})/@ConfigurationPropertiesScan({"parseconfiguration"})
* -或配合注册为Bean:@Configuration/@Component,或再引入配置处理器依赖:spring-boot-configuration-processor
* -属性需要Get/Set方法支持
* -可以注入任意类型数据,自动转换注入
* -无法识别或类型无法转换,会导致配置失败,会报错;没配置则不注入
*
* @author Chenghe Xu
* @date 2023/2/17 9:47
*/
@Data
//@Component
//@Configuration
@ConfigurationProperties("myproperties")
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test02 {
private String name1;
// private String[] srr1;
// private String[] srr2;
// private String[] srr3;
// private List srr1;
// private List srr2;
// private List srr3;
private Set srr1;
private Set srr2;
private Set srr3;
private Map map1;
private Map map2;
private Pet pet1;
private Pet pet2;
@Test
public void test1() {
System.out.println("name1 = " + name1);
System.out.print("srr1 = |");
for (String s : srr1) {
System.out.print(s + "|");
}
System.out.println();
System.out.print("srr2 = |");
for (String s : srr2) {
System.out.print(s + "|");
}
System.out.println();
System.out.print("srr3 = |");
for (String s : srr3) {
System.out.print(s + "|");
}
System.out.println();
System.out.print("map1 = |");
map1.forEach((k, v) -> {
System.out.print(k + "=");
System.out.print(v + "|");
});
System.out.println();
System.out.print("map2 = |");
map2.forEach((k, v) -> {
System.out.print(k + "=");
System.out.print(v + "|");
});
System.out.println();
System.out.println("pet1 = " + pet1);
System.out.println("pet2 = " + pet2);
}
}
@SpringBootTest(classes = SubGenericityApplication.class)
class Test02_1 {
@Autowired
private Test02 test02;
@Test
public void test1() {
System.out.println("test02.getName1() = " + test02.getName1());
System.out.println("test02.getSrr1() = " + test02.getSrr1());
System.out.println("test02.getSrr2() = " + test02.getSrr2());
System.out.println("test02.getSrr3() = " + test02.getSrr3());
System.out.println("test02.getMap1() = " + test02.getMap1());
System.out.println("test02.getMap2() = " + test02.getMap2());
System.out.println("test02.getPet1() = " + test02.getPet1());
System.out.println("test02.getPet2() = " + test02.getPet2());
}
}
/**
* @PostConstruct
* 实现全局静态变量访问优化
* -可以优化重复的@Autowired注解,直接静态访问
*/
@Component
class ConfigurationUtil {
public static Test02 staticTest02;
@Autowired
public Test02 test02;
@PostConstruct
public void initialize() {
System.out.println("==Spring容器启动时初始化该方法==");
staticTest02 = this.test02;
}
}
@SpringBootTest(classes = SubGenericityApplication.class)
class Test02_2 {
@Test
public void test1() {
System.out.println("ConfigurationUtil.staticTest02.getName1() = " + ConfigurationUtil.staticTest02.getName1());
System.out.println("ConfigurationUtil.staticTest02.getSrr1() = " + ConfigurationUtil.staticTest02.getSrr1());
System.out.println("ConfigurationUtil.staticTest02.getSrr2() = " + ConfigurationUtil.staticTest02.getSrr2());
System.out.println("ConfigurationUtil.staticTest02.getSrr3() = " + ConfigurationUtil.staticTest02.getSrr3());
System.out.println("ConfigurationUtil.staticTest02.getMap1() = " + ConfigurationUtil.staticTest02.getMap1());
System.out.println("ConfigurationUtil.staticTest02.getMap2() = " + ConfigurationUtil.staticTest02.getMap2());
System.out.println("ConfigurationUtil.staticTest02.getPet1() = " + ConfigurationUtil.staticTest02.getPet1());
System.out.println("ConfigurationUtil.staticTest02.getPet2() = " + ConfigurationUtil.staticTest02.getPet2());
}
}
@Data
class Pet {
private String name;
private Integer age;
@Override
public String toString() {
return "|name=" + name + "|age=" + age + '|';
}
}
配置文件:
#####自定义解析类,直接暴力读取yml配置文件#####
# 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)
properties.username1=大傻逼
# 数组/集合(Arrays/List/Set)
arrys.srr1=1,2,3,4,5
arrys.srr2=1.1,2.2,3.3,4.4,5.5
# 键值对(Map)
maps.map1.key1=vlaue1
# 对象(Object)
pets.pet1.name=小汪
pets.pet1.age=1
注入/解析类:
package parseconfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
* 自定义解析类,直接暴力读取yml配置文件
*
* @author Chenghe Xu
* @date 2023/2/17 15:48
*/
public class Test05 {
public static void main(String[] args) {
// Properties properties = ConfigurationReader.properties;
Properties properties = ConfigurationReader.getProperties();
System.out.print("properties = |");
properties.forEach((k, v) -> {
System.out.print(k + "=");
System.out.print(v + "|");
});
System.out.println();
System.out.println("properties.username1 = " + ConfigurationReader.getProperty("properties.username1"));
System.out.println("arrys.srr1 = " + ConfigurationReader.getProperty("arrys.srr1"));
System.out.println("arrys.srr2 = " + ConfigurationReader.getProperty("arrys.srr2"));
System.out.println("maps.map1.key1 = " + ConfigurationReader.getProperty("maps.map1.key1"));
System.out.println("pets.pet1.name = " + ConfigurationReader.getProperty("pets.pet1.name"));
System.out.println("pets.pet1.age = " + ConfigurationReader.getProperty("pets.pet1.age"));
}
}
class ConfigurationReader {
private static final Logger LOGGER = LoggerFactory.getLogger(Test05.class);
// public static Properties properties = new Properties();
private static Properties properties = new Properties();
public static Properties getProperties() {
return properties;
}
public static String getProperty(String key){
return properties.getProperty(key);
}
/**
* static语句块的作用:
* 由于static修饰的变量或语句块会在类被加载时,仅且执行一次
* 所以可以进行调用方法初始化(静态)成员变量
* 即可以通过访问类名访问静态成员变量或其Get方法
*/
static {
init();
}
public static void init() {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
// 可解析多个配置文件
String[] paths = {"application-Test05.properties"};
for (String path : paths) {
ClassPathResource resource = new ClassPathResource(path);
// 处理中文乱码
inputStream = resource.getInputStream();
// inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
// inputStreamReader = new InputStreamReader(inputStream, "utf-8");
inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
bufferedReader = new BufferedReader(inputStreamReader);
// properties.load(inputStreamReader);
properties.load(bufferedReader);
}
// 关闭资源
inputStream.close();
inputStreamReader.close();
bufferedReader.close();
LOGGER.info("读取完成");
} catch (IOException e) {
LOGGER.error("无法读取配置文件");
}
}
}
配置文件:
#####Spring配置文件的解析类Environment获取式#####
myproperties:
es:
index:
type:
documents:
fields: 小徐001,小徐002,小徐003
注入/解析类:
package parseconfiguration;
import autowired.SubGenericityApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
/**
* Spring配置文件的解析类Environment获取式
*
* @author Chenghe Xu
* @date 2023/2/21 15:29
*/
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test06 {
// Spring配置文件的解析类
@Autowired
private Environment environment;
@Test
public void test1() {
// 直接匹配获取
String stringArrays01 = environment.getProperty("myproperties.es.index.type.documents.fields");
System.out.println("stringArrays01 = " + stringArrays01);
// 指定类型获取
String[] arrays01 = environment.getProperty("myproperties.es.index.type.documents.fields", String[].class);
System.out.print("arrays01 = |");
for (String s : arrays01) {
System.out.print(s + "|");
}
System.out.println();
// 带默认值获取
String stringArrays02 = environment.getProperty("myproperties.es.index.type.documents.fields01", "没有配置该属性");
System.out.println("stringArrays02 = " + stringArrays02);
// 综合类型和默认值
String[] arrays02 = environment.getProperty("myproperties.es.index.type.documents.fields01",
String[].class, new String[]{"小徐004","小徐005","小徐006"});
System.out.print("arrays02 = |");
for (String s : arrays02) {
System.out.print(s + "|");
}
System.out.println();
}
}