Java 如何在Spring中使用ClassPathResource加载外部文件?
我们在一个驱动器上有一个文件(C:\megzs\realm.properties)。我们希望使用Spring中提供的ClassPathResource加载此文件并读取内容。但我们看到该文件未发现异常。我们正在尝试的代码是Java 如何在Spring中使用ClassPathResource加载外部文件?,java,spring,Java,Spring,我们在一个驱动器上有一个文件(C:\megzs\realm.properties)。我们希望使用Spring中提供的ClassPathResource加载此文件并读取内容。但我们看到该文件未发现异常。我们正在尝试的代码是 Resource resource = new ClassPathResource("file:c:/megzs/realm.properties"); Properties prop = PropertiesLoaderUtils.loadProperties(resourc
Resource resource = new ClassPathResource("file:c:/megzs/realm.properties");
Properties prop = PropertiesLoaderUtils.loadProperties(resource);
这里我们使用ClassPathResource加载外部文件。ClassPathResource能否加载外部文件我们如何加载多个属性文件(一个来自类路径,另一个来自绝对路径)?我正在使用
@PropertySource()
将使用环境
对象读取属性
也许你应该尝试这种方法,但你的方法不是
错了,我有点困惑
@Configuration
@PropertySource({
"classpath:config.properties",
"file:/path/to/application.properties" //if same key, this will 'win'
})
public class AppConfig {
@Autowired
Environment env;
public void ReadProperties() {
String property1 = env.getProperty("property");
String property2 = env.getProperty("property2");
}
//if theres same key found in the second property
//file key in the second property file wiil be read
}
如果要访问基于文件的资源,请使用FileSystemResource并将其提供给PropertiesLoaderUtils.loadProperties()方法。下面的代码从文件系统读取属性文件,如果不存在,它将从类路径加载它。希望能有帮助
public static Properties getProperties(String propertyFile) {
try {
Resource resource = new FileSystemResource(propertyFile);
if (!resource.exists()) {
resource = new ClassPathResource(propertyFile);
}
return PropertiesLoaderUtils.loadProperties(resource);
} catch (Exception ignored) {
return null;
}
}
在下面的代码片段中,
屏幕截图
是src/test/resources
下的文件夹,测试类位于src/test/java
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Resource fileResource = new ClassPathResource(
"screen-shots/HomePage-attachment.png");
assertNotNull(fileResource);
如何加载多个属性文件??一个在类路径上,另一个在绝对路径上
Resource-Resource=resourceLoader.getResource(“classpath:com/testing.txt”)代码>将输出分配给资源
我正在使用PropertiesLoaderUtils加载属性。使用loadProperties()方法。此方法只接受单个资源对象。如何加载多个属性文件?我将尝试一下。我不知道如何为AppConfig创建一个对象来访问env属性或方法