2

假设我们有一个像下面这样的简单类。我们可以在/没有默认构造函数中使用它。我真的很好奇是否可以通过 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() );

    }
}

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

4

2 回答 2

1

如果您使用 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#beans-factory-collaborators

但请记住,您的 bean 的默认范围是单例的!

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

让我们创建一个“动态”bean,因此让我们将 bean 的范围设置为原型,以便在每次调用它时获得一个新的实例。

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

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

于 2014-03-11T09:27:31.213 回答
0

你应该看看FactoryBean

于 2014-03-11T15:03:41.783 回答