pojo

yv5phkfx  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(306)

假设我有这样一个pojo类:

class Foo {
    String name;
    int id;
}

如何在属性文件中指定此对象,以便执行以下操作:

Foo foo = environment.getProperty("foo", Foo.class);

我试过了,但没用:

foo.name = "My Name"
foo.id = 1234

我不想用 @ConfigurationProperties 因为我想在运行时读取属性。

bbmckpt7

bbmckpt71#

使用它v1是springboot1.x(从shardingsphere复制)

private static Object v1(Environment environment, String prefix, boolean handlePlaceholder) {
    try {
        Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
        Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
        Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
        Object resolverObject = resolverConstructor.newInstance(environment);
        String prefixParam = prefix.endsWith(".") ? prefix : prefix + ".";
        Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class);
        Map<String, Object> dataSourceProps = (Map)getSubPropertiesMethod.invoke(resolverObject, prefixParam);
        Map<String, Object> propertiesWithPlaceholderResolved = new HashMap();
        Iterator var11 = dataSourceProps.entrySet().iterator();

        while(true) {
            while(var11.hasNext()) {
                Entry<String, Object> entry = (Entry)var11.next();
                String key = (String)entry.getKey();
                Object value = entry.getValue();
                if (handlePlaceholder && value instanceof String && ((String)value).contains("${")) {
                    String resolvedValue = (String)getPropertyMethod.invoke(resolverObject, prefixParam + key);
                    propertiesWithPlaceholderResolved.put(key, resolvedValue);
                } else {
                    propertiesWithPlaceholderResolved.put(key, value);
                }
            }

            return Collections.unmodifiableMap(propertiesWithPlaceholderResolved);
        }
    } catch (Throwable var16) {
        throw var16;
    }
}

private static Object v2(Environment environment, String prefix, Class<?> targetClass) {
    try {
        Class<?> binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder");
        Method getMethod = binderClass.getDeclaredMethod("get", Environment.class);
        Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class);
        Object binderObject = getMethod.invoke((Object)null, environment);
        String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix;
        Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass);
        Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get");
        return resultGetMethod.invoke(bindResultObject);
    } catch (Throwable var10) {
        throw var10;
    }
}

相关问题