首页 > 其他分享 >JadConfig classpathRepository 扩展

JadConfig classpathRepository 扩展

时间:2022-10-03 15:35:04浏览次数:75  
标签:String 扩展 source classpathRepository RepositoryException JadConfig throws name

JadConfig 默认包含了基于内存,properties 文件,系统属性,以及环境变量的Repository,但是对于classpath 的文件处理不是很方便
我们可以自己在扩展

接口实现定义

 

public interface Repository {

 

/**
* Opens the configuration repository, e. g. create a database connection, open a file on disk for reading
*
* @throws RepositoryException If an error occurred while opening the data source
*/
void open() throws RepositoryException;

 

/**
* Reads the configuration parameter {@literal name} from the backing data source. The {@literal name} is specific
* to the underlying data source.
*
* @param name The parameter name
* @return The value of the provided {@literal name} as {@link String}
*/
String read(String name);

 

/**
* Closes the underlying data source when it isn't require any more.
*
* @throws RepositoryException If an error occurred while closing the underlying data source
*/
void close() throws RepositoryException;
}

参考实现

public class ClassPathRepository implements Repository {
private final Properties PROPERTIES = new Properties();

 

private String fileName = null;

 

public ClassPathRepository(String filename) {
this.fileName = filename;
}

 

@Override
public void open() throws RepositoryException {
if (fileName == null) {
throw new RepositoryException("Properties file must not be null!");
}
InputStream inputStream = null;
try {
inputStream = ClassPathRepository.class.getClassLoader().getResourceAsStream(fileName);
PROPERTIES.load(inputStream);
catch (IOException ex) {
throw new RepositoryException("Couldn't open properties file: " + fileName, ex);
finally {
if (inputStream != null) {
try {
inputStream.close();
catch (IOException e) {
// Intentionally empty
}
}
}

 

}

 

@Override
public String read(String name) {
return PROPERTIES.getProperty(name);
}

 

@Override
public void close() throws RepositoryException {

 

使用

JadConfig jadConfig = new JadConfig(new ClassPathRepository("app.properties"),bean);
jadConfig.process();

说明

以上是一个简单的classpathRepository实现,实际上我们也可以基于其他文件扩展,比如yaml ,nacos 等,可以方便的实现配置管理,JadConfig 对于配置的管理方式还是很支持的借鉴学习的,比如dremio 对于配置也实现了类似的能力,包含check,validator。。。。

参考资料

​https://github.com/Graylog2/JadConfig​

标签:String,扩展,source,classpathRepository,RepositoryException,JadConfig,throws,name
From: https://blog.51cto.com/rongfengliang/5730369

相关文章