Spring架構學習記錄之構造注入
CreateBy:雀雀
Date:2018.5.29
概念(圖檔來源于網絡):
Spring 架構為有參構造的參數指派
<?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="userDao" class="dao.impl.UserDaoImpl"></bean> <bean id="userService" class="service.impl.UserServiceImpl"> <!--通過constructor-arg元素為構造方法裡的參數指派--> <constructor-arg> <ref bean="userDao"/> </constructor-arg> </bean> </beans> |
Spring架構P命名空間 = 給屬性指派的一種方式
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- 使用p命名空間注入屬性值 --> <bean id="user" class="entity.User" p:username="張三" p:age="23" p:email="[email protected]" /> <bean id="userDao" class="dao.impl.UserDaoImpl" /> <bean id="userService" class="service.impl.UserServiceImpl" p:dao-ref="userDao" /> </beans> |
Spring架構 各種資料類型的注入方式
<?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-3.2.xsd"> <bean id="entity" class="entity.TestEntity"> <!-- 使用<![CDATA[]]>标記處理XML特殊字元 --> <property name="specialCharacter1"> <value><![CDATA[P&G]]></value> </property> <!-- 把XML特殊字元替換為實體引用 --> <property name="specialCharacter2"> <value>P&G</value> </property> <!-- 定義内部Bean --> <property name="innerBean"> <bean class="entity.User"> <property name="username"> <value>Mr. Inner</value> </property> </bean> </property> <!-- 注入List類型 --> <property name="list"> <list> <!-- 定義List中的元素 --> <value>足球</value> <value>籃球</value> </list> </property> <!-- 注入數組類型 --> <property name="array"> <list> <!-- 定義數組中的元素 --> <value>足球</value> <value>籃球</value> </list> </property> <!-- 注入Set類型 --> <property name="set"> <set> <!-- 定義Set或數組中的元素 --> <value>足球</value> <value>籃球</value> </set> </property> <!-- 注入Map類型 --> <property name="map"> <map> <!-- 定義Map中的鍵值對 --> <entry> <key> <value>football</value> </key> <value>足球</value> </entry> <entry> <key> <value>basketball</value> </key> <value>籃球</value> </entry> </map> </property> <!-- 注入Properties類型 --> <property name="props"> <props> <!-- 定義Properties中的鍵值對 --> <prop key="football">足球</prop> <prop key="basketball">籃球</prop> </props> </property> <!-- 注入空字元串值 --> <property name="emptyValue"> <value></value> </property> <!-- 注入null值 --> <property name="nullValue"> <null/> </property> </bean> </beans> |