Results 1 to 5 of 5

Thread: Avoiding constructor confusion

  1. #1
    Join Date
    Jul 2012
    Posts
    4

    Default 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. #2

    Default

    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.

  3. #3
    Join Date
    Jul 2012
    Posts
    4

    Default

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

  4. #4

    Default

    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 at 01:21 AM.

  5. #5
    Join Date
    Jul 2012
    Posts
    4

    Default

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •