1

I have an interface IpersonService with 2 implementation

public Interface IPersonService {

    public List<Person> readPersons();

}

@Service
public class FilePersonService implements IPersonService {
    public List<Person> readPersons(){
      //read from File
    }
}

and

@Service
public class DbPersonServiceimplements ICaseService{
    @Autowired
    PersonRepository repository
    public List<Person> readPersons(){
       //read from database
       return repository.findAll()
    }
}

From my controller, i would like to Autowire a ICaseService depending of a value read from application.properties files.

@RestController
public class Personcontroler {
    @Value("${database.type}")
    String dbType;
    @Autowired
    IpersonService personService;
  
    @GetMapping("/persons")
    public List<Person> readAllPersons(){
        //the person service instance depend of the dbType read from application.properties file
        return personService.readPersons()
    }
}

so depending on thr config value, i would like to have either a FilePersonService , or a DbPersonService.

How can i achive it please?

thanks so much

blaiso
  • 347
  • 4
  • 6
  • 15
  • 1
    https://reflectoring.io/spring-boot-conditionals/ or this https://stackoverflow.com/questions/65738288/how-to-dynamically-autowire-beans-in-spring-with-annotations/65751721#65751721 or this https://www.baeldung.com/spring-qualifier-annotation – Harry Coder Mar 13 '23 at 19:36

1 Answers1

0

You should be able to add to the service class something like:

@ConditionalOnProperty(
    value="IPersonService.Implementation",
    havingValue = "FilePersonService"
)

Which will only load the service class if that property is set correctly.

Welsh
  • 5,138
  • 3
  • 29
  • 43
  • Thanks for the solution, Welsh. I used the annotation the annotation @ConditionalOnProperty(value = "database.type", havingValue = "value") on every Service class and i'm able to load a service depending on my value form property file. Thanks. – blaiso Mar 14 '23 at 10:55