I am building a desktop application using JavaFx and Spring Boot and I am stuck at some problem
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 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. How can I fix this?
CodePudding user response:
According to your requirements the class Translator
should not belong to Spring-context
and it should not be a 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
.
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.
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
. 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.
The whole picture of your question seems like a design problem.