簡體   English   中英

如何通過Class獲得@Autowired JpaRepository的功能

[英]How to get the functionality of @Autowired JpaRepository by its Class

在我的春季啟動應用程序中,我有一個類'repo',它的類名稱可以找到它

Class<?> repo = Class.forName("com.example.demo.repository." + modelName + "Repository");

其中modelName是一個String。

repo.toString()返回

interface com.example.demo.repository.LaptopRepository

我希望能夠使用laptopRepository.findAll()方法。 我完全不知道我將擁有哪個modelName。 所以我不能在方法之外使用@Autowired注釋。

相反,我想在方法中使用laptopRepository,它接受modelName屬性。

@GetMapping("/administration")
public String getModelInstances(@RequestParam("modelName")String modelName, Model model) throws ClassNotFoundException {
    Class<?> repo = Class.forName("com.example.demo.repository." + modelName + "Repository");

    // @Autowired
    // repo repoRepository;

    model.addAttribute("objects", repoRepositories.findAll());
    return "administration";
}

只需使用Sping應用程序上下文按類型獲取所需的存儲庫bean。

1)在控制器中自動跟蹤上下文

@Autowired
private ApplicationContext appContext;

2)在您的方法中使用它

appContext.getBean(Class.forName("com.example.demo.repository." + modelName + "Repository"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM