簡體   English   中英

使用Spring在工廠中使用具有相同接口的注入bean的最佳方法是什么?

[英]What is the best approach to get injected beans with same interface in factory using Spring?

我創建了一個工廠,根據一些條件檢查來決定應返回哪種最佳實施。

// Factory
@Component
public class StoreServiceFactory {

    @Autowired
    private List<StoreService> storeServices;

    public StoreService getService(){

        if(isActiveSale){
            return storeServices.get("PublicStoreService")
        }

        return storeServices.get("PrivateStoreService")
    }
}

//Service Implementations
@Service
@Qualifier("PublicStoreService")
public class PublicStoreService implements StoreService {

    public getStoreBalanceScore(){
        Do Stuff....
    }
}

@Service
@Qualifier("PrivateStoreService")
public class PrivateStoreService implements StoreService {

    public getStoreBalanceScore(){
        Do Stuff....
    }
}


    // Controller
    @Autowired
    StoreServiceFactory storeServiceFactory;

    @Override
    public StoreData getStoreBalance(String storeId) {
        StoreService storeService = storeServiceFactory.getService();
        return simulationService.simulate(sellerId, simulation);
    }

這種方法好嗎? 如果是,我如何以一種優雅的方式獲得服務? 我只想使用注釋,而不使用配置。

您應該使用映射而不是List,並將字符串參數傳遞給getService方法。

public class StoreServiceFactory {

    @Autowired
    private Map<String,StoreService> storeServices = new HashMap<>();

    public StoreService getService(String serviceName){

        if(some condition...){
            // want to return specific implementation on storeServices map, but using @Qualifier os something else
            storeServices.get(serviceName)
        }
    }
}

您可以使用支持的實現來預填充地圖。 然后,您可以獲取適當的服務實例,如下所示:

    // Controller
    @Autowired
    StoreServiceFactory storeServiceFactory;

    @Override
    public StoreData getStoreBalance(String storeId) {
        StoreService storeService = storeServiceFactory.getService("private");//not sure but you could pass storeId as a parameter to getService
        return simulationService.simulate(sellerId, simulation);
    }

如果您不喜歡使用字符串,則可以為受支持的實現定義一個枚舉,並將其用作映射的鍵​​。

您無需在代碼上創建列表或映射。 您可以使用GenericBeanFactoryAccessor從Spring上下文直接檢索它。 這有多種方法來檢索特定的bean,例如基於名稱,注釋等。您可以在此處查看javadoc。 這避免了不必要的復雜性。

http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM