美文网首页
在非spring bean里读取properties代替@Val

在非spring bean里读取properties代替@Val

作者: lfboo | 来源:发表于2021-10-21 21:20 被阅读0次

在spring bean中,我们一般使用@Value来读取配置文件中的property, 但如果想在非spring bean中读取property,可以使用这里提供的一种方法:

@Component
public class PropertiesUtils implements EmbeddedValueResolverAware {
    private static StringValueResolver stringValueResolver;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        PropertiesUtils.stringValueResolver = stringValueResolver;
    }

    public static String getPropertyValue(String propertyName) {
        String finalPropertyName = "${"+propertyName+"}";
        return PropertiesUtils.stringValueResolver.resolveStringValue(finalPropertyName);
    }
}

这里借助EmbeddedValueResolverAware,拿到StringValueResolver, 这里需要注意的点是 要查的propertyName须是${xxx}这种格式的,@Value的实现也是基于StringValueResolver

public class TestPropertiesTest {
    public static void main(String[] args) {
        String str = PropertiesUtils.getPropertyValue("test.name");
        System.out.println(str);
    }
}

相关文章

网友评论

      本文标题:在非spring bean里读取properties代替@Val

      本文链接:https://www.haomeiwen.com/subject/lauhaltx.html