2017-07-30 47 views
0

在應用程序療法是多個屬性文件用於管理的異常信息,警示和其他一些文字,這些文件是這樣的: - core-message.properties - databaseException.properties .... ..Find消息文件

在服務層可能會發生數據庫調用,並且數據庫返回一個屬性文件中存在的鍵,我想要獲取值並將異常消息提交給用戶界面層。

,如果我知道,在至極性能的關鍵文件中的代碼將是這樣的:

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

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

我覺得春天能做到這一點,因爲當我使用的彈簧:在JSP文件信息標籤彈簧不知道鍵入女巫文件,但它正確加載消息。

+0

可以加載所有屬性1個屬性對象?另請參閱https://stackoverflow.com/questions/3403773/using-multiple-property-files-via-propertyplaceholderconfigurer-in-multiple-pr – user7294900

+0

我加載它,但在服務端我不能定義@value –

回答

0

拿到鑰匙的值編程,您可以使用以下方法:

@Autowired 
private Environment env; 
... 
String something = env.getProperty("property.key.something"); 
+0

它給我空爲我的屬性文件中存在的關鍵 –

1

你可以使用Spring Environment抽象了點。

首先,你需要財產來源添加到您的Java配置文件

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

或者,如果您有多個屬性文件

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

添加PropertySourceConfigurer到Java的配置文件

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

現在我們假設在您的core-message.properties您有以下數據

message.name=Hello 

您可以通過自動裝配Environment抽象,然後調用env.getProperty()

@Autowired 
Environment env; 

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

Environment對象檢索任何豆這個數據提供界面來配置財產來源和解決性能。它爲從各種來源讀取提供了方便:屬性文件,系統環境變量,JVM系統屬性,servlet上下文參數等等,這非常有用。例如:

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