2012-05-29 103 views
0

我的許多應用程序屬性由數據庫提供,我想通過存儲庫注入它們。我想知道春天是否可以做到這一點。如果有人能夠提出解決方案,我會很高興。我正想着代碼看起來liek這樣的:彈簧設置存儲庫

@Component 
    public class ExampleService implements Service { 

     private PlatformSetting setting1; 

     @Required 
     @Qualifier("setting1") 
     public void setSetting1(PlatformSetting setting1) { 
      this.setting1 = setting1; 
     } 

     public String getMessage() { 
      return "Hello world!" + setting1.getValue();  
     } 

    } 


    @Repository 
    public class PlatformSettingRepository { 


     private HashMap<String, PlatformSetting> settings; 
     { 
      settings = new HashMap<String, PlatformSetting>(); 
      settings.put("setting1", new PlatformSetting("bla1")); 
      settings.put("setting2", new PlatformSetting("bla2")); 

     } 

     @Bean 
     public PlatformSetting findSetting(@Qualifier String qual) { 
      return settings.get(qual); 
     } 
    } 

我知道我可以只注射PlatformSettingRepositoy到服務來關注一下吧。但我不希望在調用時進行這些查找,我希望Spring容器在啓動時執行它們。

回答

1

使用Spring表達式語言。

第1步:使您的設置的HashMap使用@Bean,讓使用id = 「的appSettings」

第2步說:現在您要設置1注,只需使用註釋:

@Value("#{ appSettings['setting1'] }") 
private PlatformSetting setting1; 

注意:這適用於普通的值,它也適用於你的情況。雖然我沒有嘗試過。 如果這不起作用,你可以直接在你的方法中使用表達式分析器,因爲你已經使用了java配置方式來初始化bean。

+0

謝謝,這正是我一直在尋找的 – cproinger

3

PropertyPlaceholderConfigurer與CommonsConfigurationFactory結合是您的答案。請看看this的帖子。

0

您可以使用InitializingBean

@Component 
public class Config implements InitializingBean { 

    /** 
    * Used to hold app properties. 
    */ 
    private Properties properties = new Properties(); 

    //Getters, setters and filling properties from where you need 

    public void afterPropertiesSet() throws Exception { 
     //Initialize some static properties of other objects here. 
    } 
} 

比注入配置到其他類。