OneXer
OneXer

Reputation: 355

Spring problems injecting Clock as a constructor argument

I have a class that takes a java.time.Clock object as a constructor argument. I am having problems defining this as a bean in the applicationContext.xml file:

TimeTracker.java

public class TimeTracker{

    public final Clock clock;
    public TimeTracker(Clock clock){
        this.clock = clock;
    }

applicationContext.xml

<bean id="timeTracker" 
        class="com.tracker.TimeTracker">
        <constructor-arg type="java.time.Clock" value=""/> 
</bean>

The error I am having is: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

Upvotes: 1

Views: 2339

Answers (5)

Tomek Samcik
Tomek Samcik

Reputation: 546

Strelok's answer almost works, it should be -

<bean name=“clock” class=“java.time.Clock” factory-method=“systemDefaultZone” />

Upvotes: 0

borjab
borjab

Reputation: 11655

The solution from Strelok nearly works but it failed for me as you do not need to define the full path of the factory method. It is relative to the factory Class so if you type factory-method=“java.time.Clock.systemDefaultZone” it will look for a method in java.time.Clock.java.time.Clock.systemDefaultZone().

<bean id="systemClock" class="java.time.Clock" factory-method="systemUTC" />

<bean id="timeTracker" class="com.tracker.TimeTracker">
    <constructor-arg type="java.time.Clock" ref="systemClock"/> 
</bean>

To makes things worse the Spring exception is not especially helpful.

Upvotes: 0

Strelok
Strelok

Reputation: 51461

Try it like this:

<bean class=“java.time.Clock” factory-method=“java.time.Clock.systemDefaultZone” name=“clock”/>

<bean id="timeTracker" 
    class="com.tracker.TimeTracker">
    <constructor-arg ref=“clock”/> 
</bean>

The value attribute is for primitive types only.

Upvotes: 3

Antho Christen
Antho Christen

Reputation: 1329

Try,

<bean id="timeTracker" class="com.tracker.TimeTracker">
        <constructor-arg>
          <bean class="java.time.Clock" factory-method="java.time.Clock.systemUTC" /> 
        </constructor-arg>
</bean>

Upvotes: 0

Ayub Malik
Ayub Malik

Reputation: 2578

You need to instantiate a clock and use it as a reference. Something similar to:

<bean id="clock" class="java.time.clock"/>
<bean id="timeTracker" 
    class="com.tracker.TimeTracker">
    <constructor-arg type="java.time.Clock" ref="clock"/> 
</bean>

Upvotes: 0

Related Questions