The following example uses the p-namespace for even more succinct XML configuration.
<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.xsd">
<bean id="userService" class="com.xx.UserServiceImp">
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="masterkaoli"
P:userService-ref="userService"/> <!-对于引用类的使用 -ref -->
<!--使用p 命名空间 来替代 </property> -->
<!--上下两个bean 定义含义相同 -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy- method="close">
<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="masterkaoli"/>
<property name="userService" ref="userService"/>
</bean>
</beans>
The preceding XML is more succinct; however, typos are discovered at runtime rather than design time, unless you use an IDE such as IntelliJ IDEA or the Spring Tool Suite (STS) that support automatic property completion when you create bean definitions. Such IDE assistance is highly recommended.
注:使用 p 命名空间可以代替< property > 对于引用类的使用 -ref但是 typos are discovered at runtime rather than design time 错别字 只能在运行时才能发现,编译无法识别,除非使用强大的IDE 如 IDEA 或STS
c-namespace(Spring 3.1及以后出现)
在XML配置文件中,首先引入如下命名空间:
xmlns:c=”http://www.springframework.org/schema/c”
然后,在对应的中,以的c:属性(具体名称可定制),而非子元素,配置其所依赖的其他Spring Bean
示例如下:
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
<constructor-arg value="foo@bar.com"/>
</bean>
等价于:
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="foo@bar.com"/>
注意对比上述示例,特别是c:bar-ref, c:baz-ref和c:emial属性的用法。