Choose which implementation to inject at runtime spring

后端 未结 1 1722
温柔的废话
温柔的废话 2020-12-06 08:01

I have the following classes:

public interface MyInterface{}

public class MyImpl1 implements MyInterface{}

public class MyImpl2 implements MyInterface{}

p         


        
1条回答
  •  一向
    一向 (楼主)
    2020-12-06 08:30

    Declare implementations with @Component("implForRq1") and @Component("implForRq2")

    Then inject them both and use:

    class Runner {
    
        @Autowired @Qualifier("implForRq1")
        private MyInterface runnerOfRq1;
    
        @Autowired @Qualifier("implForRq2")
        private MyInterface runnerOfRq2;
    
        void run(int rq) {
            switch (rq) {
                case 1: runnerOfRq1.run();
                case 2: runnerOfRq2.run();
                ...
    
            }
        }
    
    }
    
    ...
    
    @Autowired
    Runner runner;
    
    void run(int rq) {
        runner.run(rq);
    }
    

    0 讨论(0)
提交回复
热议问题