Java/Spring/Constructor Injection

Материал из Java эксперт
Версия от 06:16, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Call Constructor

       
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"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="encyclopedia"
          name="knowitall"
          class="ConfigurableEncyclopedia">
        <constructor-arg>
            <util:map>
                <entry key="AgeOfUniverse" value="13700000000"/>
                <entry key="ConstantOfLife" value="326190476"/>
            </util:map>
        </constructor-arg>
    </bean>
    <bean id="oracle" class="BookwormOracle">
        <property name="encyclopedia" ref="knowitall"/>
    </bean>
</beans>

File: Main.java
import java.util.Map;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
public class Main {
  public static void main(String[] a) {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
    Oracle oracle = (Oracle) bf.getBean("oracle");
    System.out.println("Meaning of life is " + oracle.defineMeaningOfLife());
  }
}
interface Oracle {
  String defineMeaningOfLife();
}
interface Encyclopedia {
  Long findLong(String entry);
  
}
class BookwormOracle implements Oracle {
  private Encyclopedia encyclopedia;
  public String defineMeaningOfLife() {
      Long ageOfUniverse = this.encyclopedia.findLong("AgeOfUniverse");
      Long constantOfLife = this.encyclopedia.findLong("ConstantOfLife");
      return String.valueOf(ageOfUniverse / constantOfLife);
  }
  public void setEncyclopedia(Encyclopedia encyclopedia) {
      this.encyclopedia = encyclopedia;
  }
}
class ConfigurableEncyclopedia implements Encyclopedia {
  private Map<String, Long> entries;
  public ConfigurableEncyclopedia(Map<String, Long> entries) {
      Assert.notNull(entries, "The "entries" argument cannot be null.");
      this.entries = entries;
  }
  public Long findLong(String entry) {
      return this.entries.get(entry);
  }
}





Constructor Argument And Local Reference

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="RangeService" class="RangeServiceImpl">
    <constructor-arg>
      <ref local="RangeDao"/>
    </constructor-arg>
  </bean>
  <bean id="RangeDao" class="StaticDataRangeDaoImpl">
  </bean>
</beans>

File: Main.java
import java.util.Date;
import java.util.GregorianCalendar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class Main {
  public static void main(String args[]) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
    RangeService ws = (RangeService) ctx.getBean("RangeService");
    Double high = ws.getHistoricalHigh(new GregorianCalendar(2004, 0, 1).getTime());
    System.out.println("High was: " + high);
  }
}
interface RangeService {
  Double getHistoricalHigh(Date date);
}
class RangeServiceImpl implements RangeService {
  RangeDao RangeDao;
  public RangeServiceImpl(RangeDao RangeDao) {
    this.RangeDao = RangeDao;
  }
  public Double getHistoricalHigh(Date date) {
    RangeData wd = RangeDao.find(date);
    if (wd != null)
      return new Double(wd.getHigh());
    return null;
  }
}
class RangeData {
  Date date;
  double low;
  double high;
  public Date getDate() {
    return date;
  }
  public void setDate(Date date) {
    this.date = date;
  }
  public double getLow() {
    return low;
  }
  public void setLow(double low) {
    this.low = low;
  }
  public double getHigh() {
    return high;
  }
  public void setHigh(double high) {
    this.high = high;
  }
}
interface RangeDao {
  RangeData find(Date date);
  RangeData save(Date date);
  RangeData update(Date date);
}
class StaticDataRangeDaoImpl implements RangeDao {
  public RangeData find(Date date) {
    RangeData wd = new RangeData();
    wd.setDate((Date) date.clone());
    wd.setLow(5);
    wd.setHigh(15);
    return wd;
  }
  public RangeData save(Date date) {
   return null;
  }
  public RangeData update(Date date) {
    return null;
  }
}





ConstructorCaller In ContextConfig

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="testBean" class="ConstructorTestBean">
      <constructor-arg value="Steven Devijver"/>
<!--
      <constructor-arg value="1"/>
-->
      <constructor-arg value="1" type="java.lang.Integer"/>
   </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) throws Exception {
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    ConstructorTestBean testBean = (ConstructorTestBean) beanFactory.getBean("testBean");
    System.out.println(testBean.isConstructor1Used());
    System.out.println(testBean.isConstructor2Used());
  }
}
class ConstructorTestBean {
  private boolean constructor1Used = false;
  private boolean constructor2Used = false;
  public ConstructorTestBean(String name, Integer id) {
    this.constructor1Used = true;
  }
  public ConstructorTestBean(String firstName, String lastName) {
    this.constructor2Used = true;
  }
  public boolean isConstructor1Used() {
    return this.constructor1Used;
  }
  public boolean isConstructor2Used() {
    return this.constructor2Used;
  }
}





Constructor Confusion Demo

       
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;
  }
}





SingletonScope And PrototypeScope

       
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"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="singleMe" class="java.lang.String" scope="singleton">
        <constructor-arg type="java.lang.String" value="Singleton"/>
    </bean>
    <bean id="prototypeMe" class="java.lang.String" scope="prototype">
        <constructor-arg type="java.lang.String" value="Prototype"/>
    </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 {
  private static void compare(final BeanFactory factory, final String beanName) {
    String b1 = (String)factory.getBean(beanName);
    String b2 = (String)factory.getBean(beanName);
    System.out.println("Bean b1=" + b1 + ", b2=" + b2);
    System.out.println("Same?  " + (b1 == b2));
    System.out.println("Equal? " + (b1.equals(b2)));
}
public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory(
                        new ClassPathResource("context.xml"));
    compare(factory, "singleMe");
    compare(factory, "prototypeMe");
    compare(factory, "requestMe");
}
}