Using p-namespace to supply property values in Spring Configuration

Monday, May 24, 2010

In spring, property values may be supplied to the bean via the configuration information. Here is an simple example.

In this example, BasicDataSource class is initialized in the container with the values as mentioned in the property tag. Each of the property is an instance variable in the BasicDataSource class.










There is a shortcut to mention the property values. That uses p-namespace. Here is how you need to provide the values.


destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="masterkaoli"/>


You need to ensure that the p-namespace is included in the xml declaration else you will get following error.

Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 44 in XML document from class path resource [Configuration.xml] is invalid; nested exception is org.xml.sax.SAXParseException: The prefix "p" for attribute "p:driverClassName" associated with an element type "bean" is not bound.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:378)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:316)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:284)
at org.springframework.beans.factory.xml.XmlBeanFactory.(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.(XmlBeanFactory.java:61)
at springbeansamples.CollectionTest.main(CollectionTest.java:11)

The reason for above error is missing namespace declaration. See the typical declaration below.


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
...
...
...



To solve the error include the namespace declaration as mentioned in this example below. See the line number 4.


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
...
...

0 comments:

Post a Comment

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP