Using the <property> element to assemble values and references for a bean's properties is not too complicated. Nonetheless, Spring's namespace p provides another way of assembling bean properties that doesn't require as many angle brackets to be configured.
The schema URI for namespace p is http://www.springframework.org/schema/p . If you want to use namespace p, just add the following statement to Spring's XML configuration:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:p="http://www.springframework.org/schema/p"
- 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.0.xsd">
With this declaration, we can now wire the bean's properties using p: as a prefix for all properties of the <bean> element. To demonstrate, we redeclare the kenny Bean configuration:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:conf/mybatis-config.xml" p:mapperLocations="classpath:mapper/*.xml" />
The value of the p:configLocation attribute is set to the value in "". Likewise, the value of the p:dataSource-ref attribute is set to "dataSource", and the dataSource-ref attribute will be assembled with a bean reference with an ID of dataSource. The -ref suffix serves as a flag to tell Spring that it should wire a reference instead of a literal.
The choice of <property> or namespace p is up to you, they are equivalent. The main advantage of namespace p is that it is more concise. When writing samples on fixed-width paper, choosing a namespace is relatively more appropriate. Therefore, you may see me use the namespace p from time to time throughout this book, especially when the horizontal page space is tight.
If you do not use the definition method of the P namespace and use <property>, the corresponding definition should be:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- file mapper, specify class file -->
<property name="configLocation" value="classpath:conf/mybatis-config.xml"/>
<!-- Automatically scan the mapping.xml file-->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>