0

A good practice is defining a service as an interface and its implementation on a class.

Assuming I have 2 classes which implement the same interface, and I'd like to differentiate them according a property (not to a profile). I mean, if I have @Autowire private MyServiceInterface myService; I'd like to receive an instance of PotatoServiceImpl if I have myproperty=potato or an instance of TomatoServiceImpl if I have myproperty=tomato.

I'm not using profiles.

P.S. When I say a property,I mean a property in application.properties

1 Answers1

2

Look:

public interface MyInterface {
}

@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "potato", matchIfMissing = false)
public class MyPotatoImpl implements MyInterface {
}

@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "tomato", matchIfMissing = false)
public class MyTomatoImpl implements Myinterface {
}

@Component
public class Consumer {
    @Autowire
    private MyInterface tomatoOrPotato; //depending on property myproperty value
}

This is for me a very elegant solution to implement the strategy creational design pattern spring styled. Look here for docs about @ConditionalOnProperty annotation.

Roberto Canini
  • 340
  • 1
  • 3
  • 13
  • 1
    I worked,I just would like to remark that rather than using `prefix` you have to use `name`. – Hola Soy Edu Feliz Navidad Aug 23 '19 at 13:13
  • Yes you're right. When you have a property composed by multiple parts dots separated such as `mySection.coolProperty` you can you specify `prefix` attribute as `mySection` and `name` as `coolProperty`. – Roberto Canini Aug 23 '19 at 13:16