springboot 获取配置文件中的信息
417人浏览 / 0人评论
参考:
https://www.zhangshengrong.com/p/2EaE59vBaM/
依赖 spring 的方式:
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* @Author FengHao
* @Date 2023/3/29
* @Description: 项目启动时获取配置信息,根据需要添加
**/
@Component
public class ConfigConstant {
@Autowired
private Environment env;
public static String spring_application_name;
public static String server_port;
@PostConstruct
public void readConfig() throws Exception {
Field[] fields = ConfigConstant.class.getFields();
for (Field field : fields) {
field.set(null, getProperty(field.getName().replace("_", ".")));
}
}
private String getProperty(String key) {
return new String(Objects.requireNonNull(env.getProperty(key)).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
}
}
静态代码块的方式:
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Properties;
/**
* @Author FengHao
* @Date 2023/3/29
* @Description: 不依赖spring, 单测调代码时使用
**/
public class ConfigConstantNoSpring {
public static String spring_application_name;
public static String server_port;
static {
try {
Properties props = new Properties();
props.load(new InputStreamReader(
Objects.requireNonNull(ConfigConstantNoSpring.class
.getClassLoader().getResourceAsStream("application.properties")),
StandardCharsets.UTF_8));
String profile = props.getProperty("spring.profiles.active");
String envFile = "application-" + profile + ".properties";
Properties envProps = new Properties();
envProps.load(new InputStreamReader(
Objects.requireNonNull(ConfigConstantNoSpring.class
.getClassLoader().getResourceAsStream(envFile)), StandardCharsets.UTF_8));
Field[] fields = ConfigConstant.class.getFields();
for (Field field : fields) {
field.set(null, envProps.getProperty(field.getName().replace("_", ".")));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
全部评论