0

In an application there are multiple properties file for managing exception messages, alerts, and some others text these file like this:

  • core-message.properties
  • databaseException.properties ...

in Service layer maybe a database call occurs and the database returns a key that exists in one the properties files, and I want get the value and raise the exception message to user interface layer.

if I know that the key in which properties file the code will be like this:

@Value("#{core['theExceptionKey']}") 
public String excpetionMessage; 

private void myMethod() {
throw new ExceptionClass(exceptionMessage);
}

I think spring can do that because when I use spring:message tag in jsp files spring does not know the key in which file but it loads the message correctly.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Mohammad Mirzaeyan
  • 845
  • 3
  • 11
  • 30

2 Answers2

2

You can use Spring Environment abstraction for that.

First you need to add Property Source to your Java Configuration file

@Configuration
@PropertySource("classpath:/com/mypacakge/core-message.properties")
public class AppConfig { 

Or if you have multiple properties files

@Configuration
@PropertySources({
    @PropertySource("classpath:core-message.properties"),
    @PropertySource("classpath:database.properties")
}) 
    public class AppConfig { 

Add PropertySourceConfigurer to to your Java Configuration file

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
 }

Now let's say that in your core-message.properties you have the following data

message.name=Hello

You can retrieve this data in any bean by autowiring Environment abstraction and then calling env.getProperty()

@Autowired
Environment env;

public void m1(){
String message = env.getProperty("message.name")` // will return Hello

Environment object provides interface to configure property sources and resolve properties. It provides convenience to read from a variety of sources: properties files, system environment variable, JVM system properties, servlet context parameters, and so on, which is very useful. For example :

    environment.getSystemProperties().put("message", "Hello");
    System.getProperties().put("message", "Hello");

    environment.getSystemProperties().get("message"); // retrieve property
    environment.getPropertySources() // allows manipulation of Properties objects

Spring Reference Documentation - Environment

fg78nc
  • 4,774
  • 3
  • 19
  • 32
0

To get the value of the key programmatically you can use the following:

@Autowired
private Environment env;
...
String something = env.getProperty("property.key.something");
mgyongyosi
  • 2,557
  • 2
  • 13
  • 20