Spring XML 配置中為 JdbcTemplate 注入 DataSource,兩種寫法行為不同:
<beans xmlns:p="https://www.springframework.org/schema/p" ...>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>
p:dataSource-ref 直接映射到 setDataSource(DataSource) setter 方法。dataSource 對應 JavaBean 規約 (去掉 set、首字母小寫)。<beans> 根元素引入 xmlns:p。<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<ref name="dataSource">dataSource</ref> <!-- 錯誤語法 -->
</bean>
<ref> **不能** 作為 <bean> 的直接子元素用於屬性注入。<bean> 子元素只能是 constructor-arg、property、qualifier 等,ref 僅能作為它們的屬性值或子元素。<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
name="dataSource" 對應 setter 方法。ref="dataSource" 引用容器中同名 Bean。| 寫法 | 正確性 | 推薦度 |
|---|---|---|
| p:dataSource-ref="dataSource" | ✓ | ★★★★★ 簡潔、可讀 |
| <property name="dataSource" ref="dataSource"/> | ✓ | ★★★★ 標準、通用 |
| <ref name="dataSource">...</ref> | ✗ Schema 違規 | 不可用 |
優先使用 p 命名空間,代碼更乾淨;複雜注入 (如集合、嵌套 Bean) 再用 <property>。