日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Spring构造方法注入类型歧义

發布時間:2024/9/20 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring构造方法注入类型歧义 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Spring框架中,當一個類包含多個構造函數帶的參數相同,它總是會造成構造函數注入參數類型歧義的問題。

問題

讓我們來看看這個客戶 bean 實例。它包含兩個構造方法,均接受3個不同的數據類型參數。 package com.yiibai.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 methodspublic String toString(){return " name : " +name + "\n address : "+ address + "\n age : " + age;}} 在Spring?bean 的配置文件中,通過傳遞一個“yiibai' 的名字,地址為'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.yiibai.common.Customer"><constructor-arg><value>yiibai</value></constructor-arg><constructor-arg><value>188</value></constructor-arg><constructor-arg><value>28</value></constructor-arg></bean></beans> 運行它,你期望的結果是什么? package com.yiibai.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 : yiibaiaddress : 28age : 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.yiibai.common.Customer"><constructor-arg type="java.lang.String"><value>yiibai</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 : yiibaiaddress : 188age : 28 這是一個很好的做法,顯式聲明每個構造函數參數的數據類型,以避免上述構造注入型歧義的問題。 http://www.yiibai.com/spring/constructor-injection-type-ambiguities-in-spring.html

總結

以上是生活随笔為你收集整理的Spring构造方法注入类型歧义的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。