我正在使用 JavaFx 和 Spring Boot 構建桌面應用程式,但遇到了一些問題
我有一個@Component類Translator,它擴展Task<String>并對谷歌翻譯 api 進行 api 呼叫,我想將一個自動裝配的 bean 類和一些字串引數(如源語言和目標語言)傳遞給Translator建構式。
@Component
class Translator extends Task<String>{
private TextPreprocessor textPreprocessor;
private Stirng strUrl;
private String from;
private String to;
private String text;
public Translator(@Value("${translator.api.url}" strUrl,TextPreprocessor textPreprocessor)){
this.strUrl=strUrl;
this.textPreprocessor=textPreprocessor;
}
protected String call() throws Exception{
//some code
}
}
@Component
class TextPreprocessor{
//some code
}
所以我的問題是我需要傳遞引數和Translator 建構式from,但我不能在這里這樣做,因為這些變數不能自動裝配。我怎樣才能解決這個問題?totext
uj5u.com熱心網友回復:
根據您的要求,該類Translator不應該屬于,Spring-context也不應該是spring-bean. 相反,這個類似乎應該在每次需要時由您在代碼中手動實體化,以便您可以動態傳遞欄位from、、、。totext
在您將手動實體化Translator實體的類中,您可以使用 autowiredstrUrl和textPreprocessoras 欄位,以便您始終可以使用它們來傳遞Translator您將創建的新實體。
在 1 種情況下,我會將其視為 a spring-bean,如果您將from, to,text從此類的 be 欄位移至 be 方法的引數,則為這種情況call。通過這種方式,您可以在任何時候想要呼叫 call 方法時Translator作為單例檢索,并且Spring-context可以為from,使用動態值。totext
您問題的整體情況似乎是一個設計問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/467597.html
上一篇:即使回應狀態為200,Mockmvc也會回傳空響??應正文
下一篇:如何測驗僅設定屬性的駱駝路線
