gpt4 book ai didi

java - 在spring中获取属性对象

转载 作者:行者123 更新时间:2023-12-01 09:47:25 25 4
gpt4 key购买 nike

我有一个名为xyz.properties的属性文件。现在,我可以在用 @Component 注释的类中加载此文件的各个属性,该属性工作得很好。

但是,我正在考虑使我的项目更加模块化,为此我需要将整个 xyz.properties 文件作为一个 properties 对象读取,以便我可以通过它一起。我怎样才能这样做呢?

更新

现在,我正在从文件中加载单个属性,如下所示

我的applicationContext.xml有以下条目

<context:property-placeholder location="classpath:xyz.properties" order="2" ignore-unresolvable="true"/>

然后我有各自的类(class)

@Component
public class XyzConfiguration {
@Value("${client.id}")
private String clientId;

@Value("${client.secret}")
private String clientSecret;

...
}

我所说的传递它是什么意思

现在,对于每个单独的属性,我必须在类中创建相应的字段,然后用相应的属性名称对其进行注释。通过这样做,我使我的嵌套模块非常特定于 spring 框架。有一天我可能会把这个模块放在 github 上供其他人使用,他们可能会也可能不会使用 spring 框架。对于他们来说,通过传递所需的参数(最好是 Properties 对象)来创建此模块的对象会更容易,以便我的模块能够自行获取属性。

最佳答案

您可以尝试下面的代码。

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.ResourceLoader;
import java.util.Properties;

private String fileLocator;
private Properties prop;
private ResourceLoader resourceLoader;

public void init() throws IOException {
//"fileLocator" must be set as a path of file.
final Resource resource = resourceLoader.getResource(fileLocator);

prop = PropertiesLoaderUtils.loadProperties(resource);
}

prop 将拥有属性文件中的所有值,然后您可以通过调用 prop.getProperty() 方法获取任何值。

关于java - 在spring中获取属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com