简体   繁体   English

如何使用注释动态自动装配 Spring 中的 bean?

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

A user can write down a url, and then, depending on the pattern of the url, my interface should use the correct implementation.用户可以写下 url,然后根据 url 的模式,我的接口应该使用正确的实现。 Therefore, want to dynamically change my Spring's bean logic execution depending on that url that my controller receives.因此,想要根据我的 controller 收到的 url 动态更改我的 Spring 的 bean 逻辑执行。

Here is my controller:这是我的 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();
}

My interface:我的界面:

public interface Myterface {

    void myInterface(String url);
}

and my implementations:和我的实现:

@Service
public class myImpl1 implements myInterface {

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

I already tried @Qualifier, but it is not dynamic.我已经尝试过@Qualifier,但它不是动态的。 The thing is that I will have a lot of different url patterns and therefore implementations overtime, I'd like to have to add only one class per pattern and not to have to modify anything.问题是我会有很多不同的 url 模式,因此实施超时,我想每个模式只添加一个 class 而不必修改任何东西。

You can try something like this in a configuration class or you can use @Profile annotation:您可以在配置 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;
    }

}

Check this answer for more details.检查此答案以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM