Matthew
Matthew

Reputation: 11280

Spring XML configuration - how to define Instant, BigDecimal, ... parameters?

How do I specify a constructor argument that is not a primitive value (or a simple type like a String) but still a class part of the Java library in the XML configuration file ?

The XML works so far for me for simple values, e.g.

<bean id="foo" class="app.model.provider.IFoo">
    <constructor-arg name="bar" value="baz"/>
</bean>

How do I define a dependency that requires e.g. a java.time.Instant instance in its constructor?

Upvotes: 0

Views: 965

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

Spring allows you to use factory methods to get instances.

Say you wanted to do the equivalent of

Instant.now();

you would use

<bean id="anInstant" class="java.time.Instant" factory-method="now"/>

If you want to do

Instant.parse("2015-07-24T17:10:00Z")

you would use

<bean id="anInstant" class="java.time.Instant" factory-method="parse">
    <constructor-arg value="2015-07-24T17:10:00Z" />
</bean>

However, I wouldn't create accessible Instant beans. If you need to pass them to some other bean's constructor, provide them directly, without names

<bean id="example" class="com.example.Example">
    <constructor-arg name="startTime">
        <bean class="java.time.Instant" factory-method="parse">
            <constructor-arg value="2015-07-24T17:10:00Z" />
        </bean>
    </constructor-arg>
</bean>

Upvotes: 2

Related Questions