簡體   English   中英

如何使用注釋動態自動裝配 Spring 中的 bean?

[英]How to dynamically autowire beans in Spring with annotations?

用戶可以寫下 url,然后根據 url 的模式,我的接口應該使用正確的實現。 因此,想要根據我的 controller 收到的 url 動態更改我的 Spring 的 bean 邏輯執行。

這是我的 controller:

@PostMapping(value = "/url",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
        produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<InputStreamResource> parseUrl(@RequestParam String url) throws IOException {

    myInterface.dosomething(url);

    return ResponseEntity.ok();
}

我的界面:

public interface Myterface {

    void myInterface(String url);
}

和我的實現:

@Service
public class myImpl1 implements myInterface {

   @Override
   public void doSomething(String url) {}
}

我已經嘗試過@Qualifier,但它不是動態的。 問題是我會有很多不同的 url 模式,因此實施超時,我想每個模式只添加一個 class 而不必修改任何東西。

您可以在配置 class 中嘗試類似的操作,也可以使用@Profile注釋:

@Configuration
public class MyConfig {

    @Bean
    public MyInterface createBean(String URL) {
        MyInterface bean;
    
        switch(URL) {
            case url1:
                    bean = new Implementation1();
                break;
    
            case url2:
                    bean = new Implementation2();
                break;
    
            default: bean = new DefaultImplementation();
        }
        return bean;
    }

}

檢查此答案以獲取更多詳細信息。

暫無
暫無

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

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