Spring 专题
专题目录
您的位置:java > Spring专题 > Spring构造方法注入类型歧义
Spring构造方法注入类型歧义
作者:--    发布时间:2019-11-20
在spring框架中,当一个类包含多个构造函数带的参数相同,它总是会造成构造函数注入参数类型歧义的问题。

问题

让我们来看看这个客户 bean 实例。它包含两个构造方法,均接受3个不同的数据类型参数。
package com.h3.common;

public class customer 
{
	private string name;
	private string address;
	private int age;
	
	public customer(string name, string address, int age) {
		this.name = name;
		this.address = address;
		this.age = age;
	}
	
	public customer(string name, int age, string address) {
		this.name = name;
		this.age = age;
		this.address = address;
	}
	//getter and setter methods
	public string tostring(){
		return " name : " +name + "\n address : "
               + address + "\n age : " + age;
	}

}
在spring bean 的配置文件中,通过传递一个“h3' 的名字,地址为'188',以及年龄为'28'。
<!--spring-customer.xml-->
<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-2.5.xsd">

	<bean id="customerbean" class="com.h3.common.customer">

		<constructor-arg>
			<value>h3</value>
		</constructor-arg>
		
		<constructor-arg>
			<value>188</value>
		</constructor-arg>
		
		<constructor-arg>
			<value>28</value>
		</constructor-arg>
        </bean>

</beans>
运行它,你期望的结果是什么?
package com.h3.common;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class app 
{
    public static void main( string[] args )
    {
    	applicationcontext context = 
    	  new classpathxmlapplicationcontext(new string[] {"spring-customer.xml"});

    	customer cust = (customer)context.getbean("customerbean");
    	system.out.println(cust);
    }
}

输出结果

name : h3
 address : 28
 age : 188
其结果不是我们所期望的,第一个构造器不执行,而是第二构造函数运行。在spring参数类型'188' 能够转换成int,所以spring只是转换它,并采用第二个构造来执行,即使你认为它应该是一个字符串。
另外,如果spring不能解决使用哪个构造函数,它会提示以下错误信息
constructor arguments specified but no matching constructor 
found in bean 'customerbean' (hint: specify index and/or 
type arguments for simple parameters to avoid type ambiguities)

解决

为了解决这个问题,应该为构造函数指定的确切数据类型,通过像这样类型的属性:
<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-2.5.xsd">

	<bean id="customerbean" class="com.h3.common.customer">
	
		<constructor-arg type="java.lang.string">
			<value>h3</value>
		</constructor-arg>
		
		<constructor-arg type="java.lang.string">
			<value>188</value>
		</constructor-arg>
		
		<constructor-arg type="int">
			<value>28</value>
		</constructor-arg>
		
	</bean>

</beans>
再次运行它,现在得到你所期望的。
输出结果
name : h3
 address : 188
 age : 28

这是一个很好的做法,显式声明每个构造函数参数的数据类型,以避免上述构造注入型歧义的问题。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册