Configure Implementation Class of Abstract Factory with Spring

后端 未结 3 1708
遥遥无期
遥遥无期 2020-12-30 17:13

For my application, I have a Scale interface and multiple classes implementing this interface, for example NormalizedScale, LogScale,

3条回答
  •  隐瞒了意图╮
    2020-12-30 17:51

    As for spring 5.x there's a simpler and cleaner way of doing this. I have decided to use @ConditionalOnProperty annotation but you may choose any @Conditional* of your preference.

    Here's the thing, I've have simplified to extreme:

    public interface MyService {}
    
    @Service
    @ConditionalOnProperty(prefix = "myService", name = "Impl", havingValue = "Some")
    public class SomeService implements MyService {}
    
    @Service
    @ConditionalOnProperty(prefix = "myService", name = "Impl", havingValue = "Foo")
    public class FooService implements MyService {}
    
    @Service
    public class SimpleService {
    
      @Autowired
      SimpleService(MyService service) {
        // service instance will depend on configuration
      }
    }
    

    I'm using springboot so I've decided to use application.properties in order to set values via environment variables like this:

    myService.Impl=${MY_SERVICE_IMPL}
    

    Then, I have a fully dynamic injection based on environment variables that may be passed to a docker container for instance.

提交回复
热议问题