Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Attribute 'name' is not allowed to appear in element 'constructor-arg'

I am using hsqldb as a db in my program. I want to inject the constructor values over spring.

Here is my bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="ConnectionManager" class="at.tuwien.group2.vpm.persistence.ConnectionManager"
        scope="singleton">
        <constructor-arg name="url" value="jdbc:hsqldb:file:vpmDatabasetest" />
        <constructor-arg name="user" value="sa" />
        <constructor-arg name="password" value="" />
    </bean>

My Constructor looks like that:

public ConnectionManager(String url, String user, String password) {
    if(url == null || user == null || password == null) {
        throw new NullPointerException("Paramaeter cannot be null!");
    }
    this.url = url;
    this.user = user;
    this.password = password;
}

However, when I want to execute the code I get:

Attribute 'name' is not allowed to appear in element 'constructor-arg'

Attribute 'name' is not allowed to appear in element 'constructor-arg'

What should I use instead?

like image 775
maximus Avatar asked Dec 02 '12 13:12

maximus


2 Answers

I guess you are using Sping 2.x. Use the index attribute to specify explicitly the index of constructor arguments:

   <bean id="ConnectionManager" ...>
        <constructor-arg index="0" value="jdbc:hsqldb:file:vpmDatabasetest" />
        <constructor-arg index="1" value="sa" />
        <constructor-arg index="2" value="" />
    </bean>

Moreover, as of Spring 3.0 you can also use the constructor parameter name for value disambiguation.

like image 191
卢声远 Shengyuan Lu Avatar answered Oct 14 '22 13:10

卢声远 Shengyuan Lu


I had same problem using Spring 3.1.2 libraries. My mistake was that I used old schema location. When I changed from

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"

to

 xsi:schemaLocation="http://www.springframework.org/schema/beans 
                     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                     http://www.springframework.org/schema/aop 
                     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"

it worked fine to use named instead of indexed constructor-args.

like image 39
Mayoares Avatar answered Oct 14 '22 13:10

Mayoares