2017-07-05 54 views
1

在春季启动应用程序,我有下面的代码用于访问属性文件(errors.properties),当我访问代码,它给出了下面exeception春天开机java.util.MissingResourceException在访问属性文件

exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties 

的errors.properties文件是在src /主/资源/

下面是代码

@Configuration 
@PropertySource("classpath:errors.properties") -- tried with both the 
                entries 
@ConfigurationProperties("classpath:errors.properties") -- 
public class ApplicationProperties { 

    public static String getProperty(final String key) { 
     ResourceBundle bundle = ResourceBundle.getBundle("errors.properties"); 
     return bundle.getString(key); 
    } 
} 

我无法理解为什么它没有选择资源文件夹下的errors.properties文件,有人可以帮我吗?

回答

0

这可能对从属性文件获取值有用。但支持国际化可能没有用处。

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, ""); 
    } 
} 
+0

给出:500,“错误”:“内部服务器错误”,“异常”:“java.lang.NullPointerException”,“消息”:“无消息可用”,该条目在属性文件中可用但仍给出空指针 – user1245524

+0

@Autowired private static Environment env; env变量变为空而不是自动装配 – user1245524

+0

感谢它的工作,如果我想要使用环境变量加载多个属性文件怎么办?我应该在@PropertySource注释中声明多个文件 – user1245524

1

此问题不是特定于Spring Boot,因为ResourceBundle引发了异常。
使用ResourceBundle.getBundle()方法时,您不应该指定基于documentation的文件的扩展名,它会自动附加。

所以,正确的用法是:

ResourceBundle.getBundle("errors"); 

注:在春季启动本地化你应该使用的MessageSource而不是Java资源包。

PropertySource注释可能工作,否则它会在上下文启动时抛出异常(因为ignoreResourceNotFound未设置为false),您可以使用@Value注释将error.properties文件中的值注入到任何Spring豆。 例如

@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包括此配置。

或者,您可以直接将Environment注入到bean中,并根据Sudhakar的回答使用getProperty()。