Piotr
Piotr

Reputation: 72

Spring choose implementation at runtime from dependencies

I have 5 modules.

In App 1 I want to use only DB impl A so I include dependencies to DB interfaces and DB impl A.

In App 2 I want to use both impl. The condition to choose impl depends on every request and DB query. For example request have some token that we use to query from DB which impl choose.

Implementations from A and B are adnotated with @Repository.

I am considering to use some Holder with request scope and @Condition. But this classes from impl A and impl B cannot be change by adding new adnotations because in App 1 we cannot guarantee conditions pass.

Upvotes: 1

Views: 316

Answers (1)

davidxxx
davidxxx

Reputation: 131326

Keep it simple : in App2, inject the two DB implementation dependencies (DB impl A and DB impl B) in the bean that needs that and then for each request and according to your "rules", just use the one or the second one.
Now, if in App2, multiple beans need to use both DB implementations, defining a bean that composes them is a better alternative, it would make the code less verbose and duplicated and you could also factor out rules in this aggregator bean.

Upvotes: 1

Related Questions