[英]Spring boot java.util.MissingResourceException while accessing properties file
在春季启动应用程序中,我具有下面的代码来访问属性文件(errors.properties),当我访问代码时,它给出了以下异常:
exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties
errors.properties文件位于src / main / resources /下
下面是代码
@Configuration
@PropertySource("classpath:errors.properties") // tried with both the annotations
@ConfigurationProperties("classpath:errors.properties") // tried with both the annotations
public class ApplicationProperties {
public static String getProperty(final String key) {
ResourceBundle bundle = ResourceBundle.getBundle("errors.properties");
return bundle.getString(key);
}
}
我不明白为什么它不选择资源文件夹下的errors.properties文件,有人可以帮我吗?
这个问题并非特定于Spring Boot,因为ResourceBundle引发了异常。
使用ResourceBundle.getBundle()方法时,您不应基于文档指定文件扩展名,它将自动添加。
因此正确的用法是:
ResourceBundle.getBundle("errors");
注意:为了在Spring Boot中进行本地化,您可能应该使用MessageSource而不是Java ResourceBundle。
PropertySource批注可能有效,否则它将在上下文启动时引发异常(由于ignoreResourceNotFound未设置为false),因此您可以使用@Value批注将来自error.properties文件的值注入到任何Spring bean中。 例如
@Configuration
@PropertySource("classpath:error.properties")
public class ApplicationProperties {
@Value("${property.in.errors.properties}")
private String propertyValue;
@PostConstruct
public void writeProperty() {
System.out.println(propertyValue);
}
}
如果看不到属性值,请确保ComponentScan包含此配置。
或者,您可以将环境直接注入bean并根据Sudhakar的回答使用getProperty()。
这对于从属性文件获取值可能很有用。 但是对于支持i18n可能不是有用的。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* This class loads the property file and returns the property file values.
*
*/
@Component
@Configuration
@PropertySource("classpath:errors.properties")
public class ApplicationProperties {
@Autowired
private Environment env;
public static String getProperty(final String key) {
return env.getProperty(key, "");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.