Search code examples
javaspringjavabeans

Can you assign a value directly to a bean in Spring?


I am trying to reproduce an assignment in Java code with an equivalent bean definition in Spring. As far as I can tell, though, Spring only lets you assign values to the fields within an object (provided that the class defines the appropriate setter methods). Is there a way to simply capture a reference to an object using Spring beans?

Here's an example of how I would expect this to work:

<!-- Non-working example. -->
<bean id="string" class="java.lang.String">
    <value>"I am a string."</value>
</bean>

I realize that in this particular case I could just use a <constructor-arg>, but I'm looking for more general solution, one that also works for classes that don't provide parameterized constructors.


Solution

  • The thing to use here is a factory-method, possibly in conjunction with a factory-bean. (Non-static functions must be instantiated by a bean of the appropriate type.) In my example problem, I wanted to capture the output of a function that returns a String. Let's say the function looks like this:

    class StringReturner {
        public String gimmeUhString(String inStr) {
            return "Your string is: " + instr;
        }
    }
    

    First I need to create a bean of type StringReturner.

    <bean name="stringReturner" class="how.do.i.java.StringReturner" />
    

    Then I instantiate my String bean by calling the desired function as a factory-method. You can even provide parameters to the factory method using <constructor-arg> elements:

    <bean id="string" factory-bean="stringReturner" factory-method="gimmeUhString">
        <constructor-arg>
            <value>I am a string.</value>
        </constructor-arg>
    </bean>
    

    This is (for my purposes) equivalent to saying:

    StringReturner stringReturner = new StringReturner();
    String string = stringReturner.gimmeUhString("I am a string.");