[英]How to pass parameter to a @Component class which can't be autowired in Spring Boot
I am building a desktop application using JavaFx and Spring Boot and I am stuck at some problem我正在使用 JavaFx 和 Spring Boot 构建桌面应用程序,但遇到了一些问题
I have @Component
class Translator
which extends Task<String>
and makes an api call to google translation api and I want to pass an autowired bean class and some string parameters such as source and target language to the Translator
constructor.我有
@Component
class Translator
,它扩展了Task<String>
并对谷歌翻译 api 进行了 api 调用,我想将自动装配的 bean class 和一些字符串参数(例如源语言和目标语言)传递给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
}
So my problem is I need to pass parameters from
, to
and text
to Translator constructor but I can't do that here because these varibles can't be autowired.所以我的问题是我需要将参数
from
、 to
和text
传递给 Translator 构造函数,但我不能在这里这样做,因为这些变量不能自动装配。 How can I fix this?我怎样才能解决这个问题?
According to your requirements the class Translator
should not belong to Spring-context
and it should not be a spring-bean
.根据您的要求, class
Translator
不应该属于Spring-context
,也不应该是spring-bean
。 Instead it seems that this class should be instantiated manually by you in the code each time you need it so that you can pass dynamically the fields from
, to
, text
.相反,似乎这个 class 应该在您每次需要它时由您在代码中手动实例化,以便您可以动态传递字段
from
, to
, text
。
In the class where you will manually instantiate Translator
instances, you could have autowired strUrl
and textPreprocessor
as fields, so that they are always available for you to pass in the new instance of Translator
that you will create.在您将手动实例化
Translator
实例的 class 中,您可以将strUrl
和textPreprocessor
自动装配为字段,以便您始终可以使用它们来传递您将创建的Translator
的新实例。
There is 1 case where I would see it as a spring-bean
and this would be if you moved from
, to
, text
from been fields of this class into been parameters of method call
.在 1 种情况下,我会把它看作一个
spring-bean
,如果你from
这个 class 的 been 字段移动to
text
到 been parameters of method call
。 This way you could have Translator
as a singleton retrieved from Spring-context
and you could use dynamic values for from
, to
, text
any time you would like to invoke call method.通过这种方式,您可以将
Translator
作为 singleton 从Spring-context
检索,并且可以在任何时候调用 call 方法时为from
、 to
、 text
使用动态值。
The whole picture of your question seems like a design problem.你的问题的全貌似乎是一个设计问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.