Yi Qian
Yi Qian

Reputation: 137

Defined bean to take enum construtor-arg

A connection pool class used for all the data source connections. It has a static enum to indicate type of connection.

class ConnectionPool {

   public static enum Type {
     t1,
     t2,
     t3;
   }
…
}

Another class does not have default contractor, the constructor takes the Type as contractor argument

class Update {
   public Update(Type type) {
      this.type = type;
   }
...
}

In applicationContext.xml, defined a bean

<bean id="update" class="package.Update">
    <contructor-arg type="package.ConnectionPool.Type">
        <value>Type.t1</value>
    </contructor-arg>
</bean>

But I got

Error creating bean with name 'update' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [package.ConnectionPools$PoolType]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

Upvotes: 4

Views: 3256

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

This should work:

<bean id="update" class="package.Update">
    <constructor-arg type="package.ConnectionPool.Type">
        <value>t1</value>
    </constructor-arg>
</bean>

or even:

<bean id="update" class="package.Update">
    <constructor-arg type="package.ConnectionPool.Type" value="t1"/>
</bean>

or my favorite:

@Configuration
public class Config {

    @Bean
    public Update update() {
        return new Update(t1);
    }

}

Upvotes: 4

Related Questions