2

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.

LaChope
  • 183
  • 1
  • 2
  • 14
  • The most dynamic way of switching beans (AFAIK, anyway) is via a @Conditional annotation, which will switch the implementation based on environment variables. You can't switch beans at runtime because they're loaded by the Spring container during startup. What you really want here is a factory – Chris Neve Jan 15 '21 at 15:04

1 Answers1

3

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.

Harry Coder
  • 2,429
  • 2
  • 28
  • 32