Matteo Codogno
Matteo Codogno

Reputation: 1579

Spring Di via setter dynamic constructor parameters

I'm beginner with spring framework, and I'm following this tutorial to applicate DI via setter. All works fine, but I'd like add to my class CsvOutputGenerator a constructor with one dynamic parameter, passed on the fly while I getting bean from Application context.

How can I do that?

I've already change my spring configuration in this way:

...
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator">
    <constructor-arg type="java.lang.String" value="Test"/>
</bean>
...

but in this way is static value for my constructor.

Upvotes: 0

Views: 1028

Answers (3)

Hbargujar
Hbargujar

Reputation: 400

The below content is based on the above question and comments. Say u have a class URLRepo with attribute String url. url is initialized to value. Then you can do something like this, to wire your CsvOutputGenerator

public class URLRepo {
     private String url = "your value";
     getters and setters
}


<bean id="urlRepo" class="com.*.*.MyURLRepo"/>    

<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator">
    <constructor-arg type="java.lang.String" value="urlRepo.url"/>
</bean>

hope this is what you are looking for.

Upvotes: 1

Andrei Stefan
Andrei Stefan

Reputation: 52366

Try something else, even though Spring isn't made to be used like this (note the "prototype" scope):

<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" scope="prototype" />

And then in your code you can do something like this:

CsvOutputGenerator myBean = (CsvOutputGenerator) context.getBean("CsvOutputGenerator", "testing testing");

This is the method in the API that I used above.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240966

You can pass it via system property for example

<constructor-arg lazy-init="true" type="java.lang.String" value="#{ systemProperties['some.key']}"/>

Upvotes: 2

Related Questions