- 当你想写一个组件又不想依赖spring boot的时,如何实现将对应的配置内容赋值到对应类中,以下数据库为事列,以下代码demo
- 在resource目录下创建db.propertise(不一定要在这个目录创建,如果要实现,命令行指定文件,可以参考apache cli来实现命令输入),文件内容如下
userName=root password=root url=www.zpl.com
- 创建对应实体类,并添加对应的get和set方法,以及重写toString()方法,代码如下
public class DataSourceModel { private String userName; private String password; private String url; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataSourceModel that = (DataSourceModel) o; return Objects.equals(userName, that.userName) && Objects.equals(password, that.password) && Objects.equals(url, that.url); } @Override public int hashCode() { return Objects.hash(userName, password, url); } @Override public String toString() { return "DataSourceModel{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + ", url='" + url + '\'' + '}'; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
- 单元测试如下
public class DataSourceModelTest { @Test public void test1() throws Exception { //创建一个对象,用于赋值操作 DataSourceModel model = new DataSourceModel(); //加载配置文件() InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.propertise"); Properties properties = new Properties(); //使用缓存流进行加载 properties.load(new BufferedInputStream(inputStream)); //获取配置类的Class对象对应的所有方法 Method[] methods = DataSourceModel.class.getMethods(); for (Method method : methods) { //获取方法名称 String methodName = method.getName(); //判断方法前缀是否是set开头 if (methodName.startsWith("set")) { //获取userName中的serName String afterName = methodName.substring(4); //获取属性第一个字母,也就是setUserName中的U String firstName = methodName.substring(3, 4); String newName = firstName.toLowerCase() + afterName; String property = properties.getProperty(newName); if (!Objects.isNull(property)) { //获取方法形参类型 Class<?>[] parameterTypes = method.getParameterTypes(); String sn = parameterTypes[0].getSimpleName(); Object arg = null; //判断属于那种数据类型 if (sn.equals("int") || sn.equals("Integer")) { arg = Integer.parseInt(property); } else if (sn.equals("long") || sn.equals("Long")) { arg = Long.parseLong(property); } else if (sn.equals("double") || sn.equals("Double")) { arg = Double.parseDouble(property); } else if (sn.equals("boolean") || sn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (sn.equals("float") || sn.equals("Float")) { arg = Float.parseFloat(property); } else if (sn.equals("String")) { arg = property; } else { continue; } //反射赋值 method.invoke(model, arg); } } } //输出 System.out.println("model = " + model); } }
- 最终结果如下