Announcement Announcement Module
Collapse
No announcement yet.
Avoiding constructor confusion Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Avoiding constructor confusion

    Hi,

    let consider a situation like this: I have bean named BeanOne and two constructors:

    Code:
    	public BeanOne(int a, String b) {
    		
    	}
    	
    	public BeanOne(String b, int a) {
    		
    	}
    How I should configure arguments 'a' and 'b' in XML file? I thought about making four <bean/> tags for them, but I assume that I would to use names of these beans for other arguments for constructors in other beans. I'm confused about this.

  • #2
    take a look at following code to see if that answers your question:
    Code:
    <bean id="bean1" class="package.BeanOne" >
    <constructor-arg type="int" value="12"/>
    <constructor-arg type="java.lang.String" value="peach"/>
    </bean>
    Code:
    <bean id="bean2" class="package.BeanOne" >
    <constructor-arg type="java.lang.String" value="apple"/>
    <constructor-arg type="int" value="14"/>
    </bean>
    bean1 and bean2 are two beans using same class (note the order of the constructor args matter). To Spring, there is no confusion here.

    Comment


    • #3
      Yeah, I thought about that, but I wondered if there is a way without defining separate beans

      Comment


      • #4
        If your business logic only needs one bean definition for the 'BeanOne' class, but you have multiple ways to construct it, consider to use setter injection.
        Last edited by tannoy; Aug 15th, 2012, 01:21 AM.

        Comment


        • #5
          I consider an abstract situation, I was just curious about mechanism of configuring Constructor Injection in Spring in many various, sometimes nonsense scenarios. Thanks anyway

          Comment

          Working...
          X