We can use either ConditionalOnProperty
or ConditionalOnExpression
to switch between two different repository implementation.
If we want to control the autowiring with simple property presence/absence or property value, then ConditionalOnProperty
can be used.
If complex evaluation is required, then we can use ConditionalOnExpression
.
ConditionalOnProperty (presence/absence of a property)
@Qualifier("specificRepo")
@ConditionalOnProperty("mongo.url")
public interface UserRepositoryMongo extends MongoRepository<User, Long>{
}
@Qualifier("specificRepo")
@ConditionalOnProperty("couch.url")
public interface UserRepositoryCouch extends CouchbasePagingAndSortingRepository<User, Long>{
}
ConditionalOnProperty (based on value)
@ConditionalOnProperty("repo.url", havingValue="mongo", matchIfMissing = true) //this will be default implementation if no value is matching
public interface UserRepositoryMongo extends MongoRepository<User, Long> {
}
@ConditionalOnProperty("repo.url", havingValue="couch")
public interface UserRepositoryCouch extends CouchbasePagingAndSortingRepository<User, Long> {
}
ConditionalOnExpression
@ConditionalOnExpression("#{'${repository.url}'.contains('couch')}")
public interface UserRepositoryCouch extends CouchbasePagingAndSortingRepository<User, Long> {
}
UPDATE
Use CrudRepository/Repository
type to inject based on your requirement.
public class DemoService {
@Autowired
@Qualifier("specificRepo")
private CrudRepository repository;
}
Based on bean created, either UserRepositoryMongo
or UserRepositoryCouch
will be autowired. Make sure only one bean is instantiated to avoid ambiguity error.