Reputation: 295
In spring boot application i have the below code for accessing the properties file(errors.properties), when I access the code it gives the below exception:
exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties
the errors.properties file is under src/main/resources/
Below is the code
@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);
}
}
I am not able to understand why its not picking up the errors.properties file under resources folder, could somebody please help me?
Upvotes: 1
Views: 1475
Reputation: 1460
This question is not specific to Spring Boot, as the exception is thrown by ResourceBundle.
When using ResourceBundle.getBundle() method you should not specify the extension of the file based on the documentation, it will be appended automatically.
So the correct usage is:
ResourceBundle.getBundle("errors");
Note: For localization in Spring Boot you probably should use MessageSource instead of Java ResourceBundle.
The PropertySource annotation probably worked, otherwise it would have thrown an exception on context startup (since ignoreResourceNotFound is not set to false), you can inject the values from your error.properties file using the @Value annotation to any Spring bean. For example
@Configuration
@PropertySource("classpath:error.properties")
public class ApplicationProperties {
@Value("${property.in.errors.properties}")
private String propertyValue;
@PostConstruct
public void writeProperty() {
System.out.println(propertyValue);
}
}
If you cannot see the property value, make sure that your ComponentScan includes this configuration.
Alternatively you can inject Environment directly to beans and use getProperty() as per Sudhakar's answer.
Upvotes: 2
Reputation: 3180
This might be useful to get the value from properties file. But may not be useful to support 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, "");
}
}
Upvotes: 0