Pages

Tuesday, May 18, 2010

How to Configure Spring beans.xml File: Basic Usage

how to configure spring beans.xml file with more flexibility

Spring is a very flexible java framework. In spring, beans are the main building bricks of an application while the bean configuration file (mostly beans.xml) acts as cement that glues the beans together.



The file beans.xml also allows beans to be initialized with particular values. For example, you can set the JDBC driver, user name, password for a java bean that is in charge of database connection in the beans.xml file as the following example.

<?xml version="1.0" encoding="UTF-8"?>
<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-2.5.xsd">

 <bean id="dbManager" class="com.mytechtip.example.DbManager">
  <property name="jdbcDriver" value="com.mysql.jdbc.Driver"/>
  <property name="jdbcUrl" value="jdbc:mysql://localhost/app"/>
  <property name="jdbcUser" value="app" />
  <property name="jdbcPassword" value="app" />
 </bean>
</beans>

So in the java class "com.example.app.DbManager", you can make JDBC connections with the fields/properties value set as in the beans.xml file. The DbManager class may look as simple as the following:
package com.mytechtip.example;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbManager {
 
 private String jdbcDriver;
 private String jdbcUrl;
 private String jdbcUser;
 private String jdbcPassword;
 
 public String getJdbcDriver() {
  return jdbcDriver;
 }
 public void setJdbcDriver(String jdbcDriver) {
  this.jdbcDriver = jdbcDriver;
 }

        // more getters and setters ...
 
 public Connection getConnection() throws Exception {
             Class.forName (getJdbcDriver()).newInstance();
             return DriverManager.getConnection(
                   getJdbcUrl(), getJdbcUser(), getJdbcPassword());
 }
}

There is one note: These properties are set after the constructor of the bean is called. So if you try to make a JDBC connection in the constructor with the fields, you will mostly get exceptions.

Anyway, this is a very simple example of the bean configuration. We will show more examples to learn the flexibility of the bean configuration in Spring.

No comments:

Post a Comment