[英]Cannot find a properties file by absolute path using Spring PropertySource
My Spring application throws FileNotFoundException
when I try to load external properties file using @PropertySource
annotation. 当我尝试使用@PropertySource
注释加载外部属性文件时,我的Spring应用程序将引发FileNotFoundException
。
Configuration class: 配置类:
@Configuration
@PropertySource(value = "file:/home/myuser/dev/app_name.properties")
public class ConfigurationClass {
@Autowired
Environment env;
public Connection getConnection() {
...
String properties = env.getProperty("cbs.url");
...
}
}
Try to give like this 尝试这样给
@PropertySource("file:/home/myuser/dev/app_name.properties")
And make sure that file available in that location . 并确保该文件在该位置可用 。
(or) (要么)
if you don't want file not found Exception when bootup your application then use below one @PropertySource("file:/home/myuser/dev/app_name.properties",ignoreResourceNotFound=true)
如果您不想在启动应用程序时找不到文件异常 ,则使用以下一个@PropertySource("file:/home/myuser/dev/app_name.properties",ignoreResourceNotFound=true)
you can override PropertySourcesPlaceholderConfigurer
bean and provide file path there. 您可以覆盖PropertySourcesPlaceholderConfigurer
bean并在那里提供文件路径。
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocations(new Resource[] {
new FileSystemResource("/some/path/file.properties"),
new FileSystemResource("/some/path/other-file.properties")
});
return configurer;
}
It can be more flexible by passing the initial path as system param or env variable. 通过将初始路径作为系统参数或env变量传递,可以更加灵活。
new FileSystemResource(System.getenv("CONFIG_PATH") + "/some/path/file.properties")
After overriding bean, your application configuration could be simple like this.(no need to specify property source) 覆盖bean之后,您的应用程序配置可以像这样简单。(无需指定属性源)
@Configuration
public class ConfigurationClass {
...
//configurations can be accessed like this
@Value("${config.variable.name}")
private String configValue;
}
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.