Tuesday, February 15, 2011

Spring: Como definir BasicDataSource usando arquivo properties

Definir um BasicDataSource usando as configurações do database definidas em arquivo properties é bem simples, basta definir um PropertyPlaceholderConfigurer.

Arquivo database.properties, com as configurações JDBC:
#usando mysql nesse exemplo
db.driver=com.mysql.jdbc.Driver
db.host=localhost
db.name=yawdb
db.username=yaw
db.password=yaw
db.port=3306
db.url=jdbc:mysql://${db.host}:${db.port}/${db.name}


spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ...>
  <bean id="dbProperties"   
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="br/com/yaw/spring/database.properties" />
  </bean>

  <bean id="myDataSource"
   class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${db.driver}" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
  </bean>
</beans>

Pronto!

@edermag
www.yaw.com.br

1 comment:

Dr. Spock said...

Vc pode usar no lugar do bean 'dbProperties' a taglib de namespace:

xmlns:context="http://www.springframework.org/schema/context"

Então, usar a tag:

<context:property-placeholder localtion="..." />