1

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?

2
  • do you have other constructors in the class time tracker? Commented Jun 13, 2018 at 9:51
  • no, I have no other constructor for the class Commented Jun 13, 2018 at 9:53

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the explanation Strelok. I tried your answer , but I get the following: Could not instantiate bean class java.time.Clock: Is it an abstract class? This is true as Clock is an abstract class
Sorry I missed the fact that the Clock constructor is protected and you have to get an instance via a factory method. I updated the answer.
0

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> 

Comments

0

Try,

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

Comments

0

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.

Comments

0

Strelok's answer almost works, it should be -

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.