Consider the old db-config file :
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
So we can see here we have hard-coded the properties of the database into the file, but rather than doing this, we can make our application more configurable, by placing these properties in the separate file and use ant-style ${property-name} syntax in xml file.
Defining the properties file
Suppose we define our db.properties file :
#db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pass=
Referring to the properties file in spring config file
Now suppose we have properties file in some external configurable file, we can simply pickup values from them.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
...
</bean>
Using the p-namespace, the same file becomes:
<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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${driver}"
p:url="${url}"
p:username="${user}"
p:password="${pass}"/>
Now once the bean is defined, we have to still tell the spring, to refer the property file location.
So this can be done in one of the 2 ways below:
Old style configuration
<!-- Old style configuration. Test one at a time by commenting the other -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:some package path/db.properties" />
</bean>
New style configuration : Use context: property-placeholder
<!-- Using context schema to achieve the same -->
<context:property-placeholder location="classpath:some-package-path/db.properties" />
No comments:
Post a Comment