我正在尝试定义一个 Map
@Service
@AllArgsConstructor
public class MyDataTablesService {
private final RegistroDtRepository registroDtRepository;
private final ContinentiDtRepository continentiDtRepository;
public Map<String, DataTablesRepository> repositories = this.createMap();
public DataTablesOutput<?> findAllDatatable(String repoId, DataTablesInput input) {
System.out.println(this.repositories);
DataTablesRepository repository = this.repositories.get(repoId);
DataTablesOutput<?> res = repository.findAll(input);
return res;
}
private Map<String, DataTablesRepository> createMap(){
Map<String, DataTablesRepository> myMap = new HashMap<String, DataTablesRepository>();
myMap.put("continenti", this.continentiDtRepository);
myMap.put("registro", this.registroDtRepository);
return myMap;
}
}
调用findAllDataTable方法,预期的输出应该是这样的
{registro=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@2aec0c10, continenti=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@1bf71fb7}
相反,在终端中,我有这个:
{registroDtRepository=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@2aec0c10, continentiDtRepository=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@1bf71fb7}
所以地图键设置不正确,当然,this.repositories.get(“Continenti”)返回null。我做错了什么?
您可以在创建地图时显式设置所需的键: 这是直接在构造函数中初始化存储库映射的代码:
private final Map<String, DataTablesRepository> repositories;
public MyDataTablesService(RegistroDtRepository registroDtRepository, ContinentiDtRepository continentiDtRepository) {
this.registroDtRepository = registroDtRepository;
this.continentiDtRepository = continentiDtRepository;
this.repositories = createMap();
}
// and the rest of your code
Spring 是 自动装配
Map<String, DataTablesRepository> repositories
所以你的 Spring 注入后存储库会被覆盖。