首先,我使用 JpaRepository
为我的实体 Foo
类创建了标准存储库,以将其存储在数据库中。
public interface FooRepository extends JpaRepository<Foo, Long> {
}
此外,作为我的第二个数据访问对象,我想使用我自己的这个简单 CRUD 操作接口(interface)的实现,它将数据存储在文件中。
public interface FooDao {
Collection<Foo> getAll();
Foo getById(Long id);
void removeById(Long id);
void update(Foo foo);
void insert(Foo foo);
}
当我像这样手动声明两个变量时,它可以正常工作
@Autowired
private FooRepository fooRepository;
@Autowired
private FooDao fooDao;
在服务中,我使用某种 switch
语句来识别当前用户选择的数据源,使用辅助变量:
private String datasource = "db"; // or "file"
但是这个解决方案需要使用 if
语句来确定我需要使用哪个数据访问对象,哪些重复代码,当然并不优雅。
public Foo getOne(Long id){
Foo result = null;
if(datasource.equals("db"))
result = fooRepository.findOne(id);
else if(datasource().equals("file"))
result = fooDao.getById(id);
return result;
}
如何在运行时在这些不同且不兼容的接口(interface)之间动态更改?如何使它们兼容以可互换使用,如何正确编写某种包装器?
最佳答案
您可以让您的 FooDao
实现实现 FooRepository
接口(interface),而不是您自己的接口(interface)。通过这种方式,您只需为接口(interface)提供两种不同的实现,并可以在您的服务中以相同的方式处理它们。它们只是两个不同的 Spring bean:
@Autowired private FooRepository fooRepository; @Autowired private FooRepository fooDao;
您的实现将如下所示:
@Component public class FooDaoImpl implements FooRepository { // your own implementations for the methods declared by FooRepository }
在您的 using 类中,您可以仅使用访问方法来获取此接口(interface)之一,如下所示:
private FooRepository getFooDataAccess() { return "db".equals(datasource) ? fooRepository : fooDao; }
关于java - 如何在运行时注入(inject)和更改数据库/数据源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49506040/