java - How is constructor chosen in spring for beans defined in xml with parent? -
i working spring 3.1.0. trying understand way spring reading xml files. trying understand how spring deals ambiguous conditions in bean definitions.
for example
i have alarm.java
package com.anshbansal.alarm2; public class alarm { private string type; private int volume; private int hour; public alarm() { } public alarm(string type, int volume, int hour) { this.type = type; this.volume = volume; this.hour = hour; } public alarm(string type, int volume) { this.type = type; this.volume = volume; } public alarm(int volume, string type) { this.type = type; this.volume = volume; } public void settype(string type) { this.type = type; } public void setvolume(int volume) { this.volume = volume; } public void sethour(int hour) { this.hour = hour; } @override public string tostring() { return "alarm{" + "type='" + type + '\'' + ", volume=" + volume + ", hour=" + hour + '}'; } }
my spring xml file alarm2.xml
follows.
<?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="propertyrandom" abstract="true"> <constructor-arg value="23" type="int"/> </bean> <bean id="alarm1" class="com.anshbansal.alarm2.alarm" parent="propertyrandom"> <constructor-arg value="10" type="int"/> <constructor-arg value="ringing" /> </bean> </beans>
there ambiguity not instantly clear int
go volume , go hour. if print following
alarm{type='ringing', volume=23, hour=10}
so how spring read xml file resolve constructor call? parent first, bean? documented somewhere?
i know there ways specifying index
, name
attributes should aware how deal such ambiguous conditions. that's why asking this.
from spring documentation,
constructor argument resolution matching occurs using argument’s type. if no potential ambiguity exists in constructor arguments of bean definition, order in constructor arguments defined in bean definition order in arguments supplied appropriate constructor when bean being instantiated.
i found following answer explains spring behavior in selecting constructor.
if specify constructor-arg without index, greediest constructor can satisfied given arguments invoked (matching arguments type). in case of java.io.file, file(string parent, string child) constructor: string argument matches both type, algorithm uses constructor.
when inheriting parent, constructor arguments merged (same merging property collections). in case, after merging child bean constructor arguments
<constructor-arg value="23" type="int"/> <constructor-arg value="10" type="int"/> <constructor-arg value="ringing" />
for ambiguous scenarios, use either index or constructor argument name.
Comments
Post a Comment