1. 程式人生 > >Spring 依賴註入

Spring 依賴註入

mage 文件中 分享圖片 array 自定義 ref pro 實體類 courier

1.構造註入

1.創建實體類User

2.創建dao層接口及兩個實現類user1daoimpl,user2daoimpl

3.創建業務層接口及實現類userbizImpl

技術分享圖片

  1. 為實現類編寫構造註入。

技術分享圖片

  1. 編寫文件頭

<?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">

  1. 在配置文件中調用。

技術分享圖片

6.測試構造註入。

p命名空間註入

1.加入文件頭

<?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.0.xsd">

2.給實體註入屬性。

<bean id="user" class="com.bdqn.entity.User"

p:id="2" p:name="隨便一個名字" p:password="自定義密碼"

>

</bean>

3.為業務層註入組件

<bean id="biz" class="com.bdqn.biz.impl.UserBizImpl" p:dao-ref="dao1">

</bean>

註意:註入組件要用p:dao-ref

其他註入

<?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="en" class="entity.TestEntity">
<!-- 使用<![CDATA[]]>標記處理XML特 殊字符 -->
<property name="specialCharacter1">
<value><![CDATA[P&G]]></value>
</property>
<!-- 把XML特殊字符替換為實體引用 -->
<property name="specialCharacter2">
<value>P&amp;G</value>
</property>
<!-- 定義內部Bean -->
<property name="innerBean">
<bean class="entity.User">
<property name="name">
<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>

Spring 依賴註入