package aaa.bbb.ccc.config;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
@Component
public class PropertiesConfig implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
String[] activeProfiles = applicationContext.getEnvironment().getActiveProfiles();
String activeProfile = "dev";
if (activeProfiles.length > 0) {
activeProfile = activeProfiles[0];
}
String fileName = StrUtil.format("config-{}.properties", activeProfile);
Properties properties = new Properties();
try {
properties.load(new ClassPathResource(fileName).getInputStream());
} catch (IOException ioException) {
throw new RuntimeException(ioException);
}
setProperties(properties);
}
private static void setProperties(Properties properties) {
Field[] fields = PropertiesConfig.class.getFields();
for (Field field : fields) {
String name = field.getName();
Class<?> type = field.getType();
try {
field.set(name, Convert.convert(type, properties.get(name)));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
spring根据activeProfile读取Properties文件配置
最新推荐文章于 2023-06-18 19:52:01 发布