Constructor Confusion Demo : Constructor Injection « Spring « Java Tutorial






File: context.xml

<?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="constructorConfusion" class="ConstructorConfusionDemo">
        <constructor-arg value="1" type="int"/>
    </bean>

</beans>

File: Main.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Main {

  public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
        "context.xml"));

    ConstructorConfusionDemo cc = (ConstructorConfusionDemo) factory
        .getBean("constructorConfusion");
    System.out.println(cc);
  }
}

class ConstructorConfusionDemo {
  private String someValue;

  public ConstructorConfusionDemo(String someValue) {
    System.out.println("ConstructorConfusionDemo(String) called");
    this.someValue = someValue;
  }

  public ConstructorConfusionDemo(int someValue) {
    System.out.println("ConstructorConfusionDemo(int) called");
    this.someValue = "Number: " + Integer.toString(someValue);
  }

  public String toString() {
    return someValue;
  }

}
  Download:  Spring-ConstructorConfusionDemo.zip( 2,599 k)








28.9.Constructor Injection
28.9.1.XML Based Bean Configuration: Constructor Injection
28.9.2.Constructor Confusion Demo
28.9.3.Constructor Caller In Context Config
28.9.4.Constructor Argument And Local Reference