Java Tutorial/Spring/Constructor Injection

Материал из Java эксперт
Перейти к: навигация, поиск

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>





Constructor Caller In Context Config

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>





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>





XML Based Bean Configuration: Constructor Injection

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>