2017-10-16 31 views
3

春天在什麼引導進樣依賴有辦法注入與在配置文件中提供的類名和構造性的依賴?春 - 基於性能

例如,我有兩個版本的通用接口,IFileStoreFileStoreAFileStoreB。我希望能夠確定其中哪些我應該在application.yml文件中使用。

我知道我可以做這樣的事情:

@Value("${fileStore.class}") 
private String fileStoreClassName; 

@Bean 
public IFileStore fileStore() { 
    switch(fileStoreClassName) { 
     case "FileStoreA": 
      return new FileStoreA(); 
     case "FileStoreB": 
      return new FileStoreB(); 
    } 
} 

然而,這感覺真的哈克。我也必須手動提取並提供任何必需的參數給他們。

我的理想是,它是能夠確定哪些基於類的名稱使用,並提供特定的人需要的任何參數,所以如果我添加第三個FileStore,它會自動神奇的工作和我」 d只需將其用於班級名稱。

+0

當你說「這是能夠確定哪些基於類的名稱使用」。它是什麼'?你是否自動連線這些物件?你如何使用FileStore? – robjwilkins

+0

是的。基本上我的實際需要直接使用它的類倒是'@Autowired IFileStore fileStore',不管底層的實現。這個例子'FileStore'只是有三個功能:'得到()','保存()'和'有()'基本「文件」的訪問(不一定是在文件系統上的實際文件)。 – samanime

回答

3

如果你真的只需要一個bean,然後創建一個條件配置

@Configuration 
@ConditionalOnProperty(name = "fileStore.class", havingValue="FileStoreA") 
public class FileStoreAConfiguration { 
    @Bean 
    public IFileStore fileStore() { 
     return new FileStoreA(...); 
    } 
} 

@Configuration 
@ConditionalOnProperty(name = "fileStore.class", havingValue="FileStoreB") 
public class FileStoreBConfiguration { 
    @Bean 
    public IFileStore fileStore() { 
     return new FileStoreB(...); 
    } 
} 

它實際上比這更容易,作爲註釋,可以使用上而不是具有單獨的配置類。

ConditionalOnProperty Javadoc

+0

這看起來很有希望。謝謝。 – samanime

2

您可以以配置相同@Bean但不同的實現方式使用Spring配置文件(@Profile註釋)。

例如,你可以做一個生產配置是這樣的:

@Configuration 
@Profile("production") 
public class ProductionConfiguration { 

    // ... 

} 

所以,你的榜樣,你可以配置你有多少個配置文件要求,然後你可以在任何通常的方式指定屬性例如,您可以將其包含在您的application.properties中。

對於進一步的細節,你可以閱讀Spring Boot features - Profiles

+0

有沒有一種方法能有這個涓滴,那種「application.yml」怎麼滑下到「應用prod.yml」?我們有相當多的環境,但只有2個不同的配置文件。每個人都有一份簡介會是一堆工作。 – samanime

0

你或許在尋找XML-based configuration

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

    <bean id="fileStore" class="com.example.FileStoreA"> 
     <property name="parameter1" value="Hello World!"/> 
    </bean> 
</beans>