地图<String, Repository>意外行为

问题描述 投票:0回答:2

我正在尝试定义一个 Map 来映射多个 JPA 存储库。这是我的代码

@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。我做错了什么?

java spring spring-boot jpa hashmap
2个回答
0
投票

您可以在创建地图时显式设置所需的键: 这是直接在构造函数中初始化存储库映射的代码:

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

0
投票

Spring 是 自动装配

Map<String, DataTablesRepository> repositories
所以你的 Spring 注入后存储库会被覆盖。

© www.soinside.com 2019 - 2024. All rights reserved.