假设我们有一个像下面这样的简单类。我们可以在/没有默认构造函数中使用它。我真的很好奇是否可以通过 Spring 框架中的构造函数将参数/参数传递给另一个对象。要解释我想要做什么,请参阅下面的代码示例。
@Component
public class Class{
String text = null;
String text2 = null;
Class( text, text2 ){
super();
this.text = text;
this.text2 = text2;
}
@Overide
public void toString(){
System.out.printf( "Text" + text + ", " + "Text2" + text2);
}
/** Methods and Setter/Getter etc. **/
}
在定义类和 Spring 注释之后,我想通过 Spring 调用这个对象。
public class Usage{
@Autowired
Class classExample;
public void method(){
String text = "text";
String text2 = "text2";
/** One way can be using setters **/
classExample.setText(text);
classExample.setText2(text2);
System.out.println( classExample.toString() );
/** Another way can be using a method **/
classExample.set(text, text2);
System.out.println( classExample.toString() );
/**What I wanted is calling it via constructor injection dynamically**/
/** Normal way we could call this **/
//classExample = new Class(text, text2);
//System.out.println( classExample.toString() );
}
}
是否可以将参数动态注入另一个对象。