2013-10-29 29 views
0
@Component 
@Qualifier("SUCCESS") 
public class RandomServiceSuccess implements RandomService{ 
    public String doStuff(){ 
     return "success"; 
    } 
} 

@Component 
@Qualifier("ERROR") 
public class RandomServiceError implements RandomService{ 
    public String doStuff(){ 
     throw new Exception(); 
    } 
} 

調用代碼Spring運行使用swap bean類

@Controller 
    public class RandomConroller { 
     @Autowired 
     private RandomService service; 
     public String do(){ 
      service.doStuff(); 
     } 
    } 

我需要做的,是基於可從http請求一些自定義的HTTP頭中檢索值,以讓他們交換。謝謝!

+1

爲什麼你不注入兩個,只使用你需要的那個? –

+0

@SotiriosDelimanolis如何在運行時交換實現?注入它們會導致Spring自動掃描並發現它們。 – Bobo

回答

3

我完全同意Sotirios Delimanolis您需要注入所有實現並在運行時選擇其中一個。

如果你有RandomService許多實現,並且不希望擾亂RandomController與選擇邏輯,那麼你可以讓RandomService實現負責選擇,如下:

public interface RandomService{ 
    public boolean supports(String headerValue); 
    public String doStuff(); 
} 

@Controller 
public class RandomConroller { 
    @Autowired List<RandomService> services; 

    public String do(@RequestHeader("someHeader") String headerValue){ 
     for (RandomService service: services) { 
      if (service.supports(headerValue)) { 
       return service.doStuff(); 
      } 
     } 
     throw new IllegalArgumentException("No suitable implementation"); 
    } 
} 

如果要定義優先級不同的實現方式,您可以使用Ordered並將注入的實現與OrderComparator一起放入TreeSet

+1

+1請注意,此模式是Spring如何解析傳遞給您的處理程序方法的參數以及它如何解析這些方法的返回值。或者,您可以實現執行邏輯的「RandomServiceProvider」。 –

+0

不理想,但我會接受這個答案。 – Bobo

1

爲什麼不注射兩種藥物,只使用你需要的那種?

@Inject 
private RandomServiceSuccess success; 

@Inject 
private RandomServiceError error; 

... 
String value = request.getHeader("some header"); 
if (value == null || !value.equals("expected")) { 
    error.doStuff(); 
} else { 
    success.doStuff(); 
} 
+0

我有超過10個不同的實現。我正在尋找只需要注入接口的解決方案。 – Bobo

0

預選賽應該用來指定要爲每一個指定不同的ID後,注入在該領域的界面的哪個實例。繼@Soritios的意見,你可以這樣做:

@Component("SUCCESS") 
public class RandomServiceSuccess implements RandomService{ 
    public String doStuff(){ 
     return "success"; 
    } 
} 

@Component("ERROR") 
public class RandomServiceError implements RandomService{ 
    public String doStuff(){ 
     throw new Exception(); 
    } 
} 


@Component 
public class MyBean{ 
    @Autowired 
    @Qualifier("SUCCESS") 
    private RandomService successService; 

    @Autowired 
    @Qualifier("ERROR") 
    private RandomService successService; 

    .... 
    if(...) 
} 

...或者你可以只獲得你從應用程序上下文要根據你的參數實例:

@Controller 
public class RandomConroller { 
    @Autowired 
    private ApplicationContext applicationContext; 

    public String do(){ 
     String myService = decideWhatSericeToInvokeBasedOnHttpParameter(); 

     // at this point myService should be either "ERROR" or "SUCCESS" 
     RandomService myService = applicationContext.getBean(myService); 

     service.doStuff(); 
    } 
} 
相關問題