• 5 Subscribers
  • 114 Views
0

I want to read from a json config file on program startup time whether to use a Mongo db backend or a postgres backend. Based on this config, I then want to inject the respective service to the controller.

I have the following interface:

public interface IItemsService {

    public void putItem();

}

And two classes which implement it:

public class MongoItemsService implements IItemsService 
{
    private SomeMongoConnection conn;

    public MongoItemsService (SomeMongoConnection conn)
    {
         this.conn = conn;
    }

    @Override
    public void putItem() {
        System.out.println("Mongo");
    }
}

and

public class PostgresItemsService implements IItemsService 
{
    private SomePostgresConnection conn;

    public PostgresItemsService(SomePostgresConnection conn)
    {
         this.conn = conn;
    }

    @Override
    public void putItem() {
        System.out.println("Postgres");
    }
}

I finally have a controller which I want to inject into:

@RestController
public class ItemsController {

    private IItemsService itemsService;

    @RequestMapping("/putitem")
        public void putItem() {
        this.itemsService.putItem();
    }

    @Autowired
    public ItemsController(IItemsService itemsService)
    {
        this.itemsService = itemsService;
    }
}

So, based on the json config, I want to inject the respective IItemsService to the controller's constructor. I would like to avoid using annotations on the individual interface and implemented services class since they may be used in other projects which do not have a strict dependency on spring. How would I dynamically set the binding of the interface to concrete class at startup time?


0 answers in total

Answer this questsion