如何通过构造器将参数传递给另一个对象,并用弹簧注释动态地传递参数



让我们有一个简单的类,如下所示。我们可以在/无默认构造函数中使用它。我真的很好奇,可以通过春季框架中的构造器传递参数/参数。要解释我想做什么,请请参阅下面的代码样本。

@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. **/
}

定义课和春季注释后,我想通过春季调用此对象。

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() );
    }
}

是否可以动态地将参数注入另一个对象。

如果使用Spring XML配置,则可以使用constructor-arg参数。

<bean id="exampleBean" class="examples.ExampleBean">
   <constructor-arg type="int" value="7500000"/>
   <constructor-arg type="java.lang.String" value="42"/>
</bean>

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#bean#beans-factory-collaborator

但请记住,豆的默认范围是单身人士!

是否可以动态地将参数注入另一个对象。

让我们创建一个"动态" bean,因此让我们将bean的范围设置为原型,以获取调用新鲜实例的evrytime。

<bean id="exampleBean" class="examples.ExampleBean" scope="prototype">
   <constructor-arg type="int" value="#{getRandomNumber}"/>
</bean>

在这种情况下,每次创建一个新的bean都会使用新的随机数创建新的bean。

您应该看看FactoryBean

最新更新