简体   繁体   中英

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. Therefore, want to dynamically change my Spring's bean logic execution depending on that url that my controller receives.

Here is my 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. 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.

You can try something like this in a configuration class or you can use @Profile annotation:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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