Jun
9
2010

How to Configure Spring beans.xml File: The Use of PropertyPlaceholderConfigurer

The file “beans.xml” used for you application is already a kind of configuration file. However, this file is designed for the developer who can quickly customize the application with less coding changes. It is not recommended for an end user to change the file.

For example, you can, of course, define the database connection properties in the beans.xml file straight away. This way, every time a user wants the application to connect to a database at a different location, the beans.xml file needs to be modified. For a complicated application, the file can grow very complicated as well. Therefore, making changes to the beans.xml file directly may not seem obvious to the end user.

Fortunately, Spring have already come up with a solution for this problem. You can define the properties in the “beans.xml” file with place holders and use the Spring provided bean PropertyPlaceholderConfigurer to replace the place holders with the value from a properties file. Here is an example of the use of PropertyPlaceholderConfigurer.

In the example from the above link, it specifies one location for the properties file with a classpath: “classpath:com/foo/jdbc.properties”. In addition to that, you can also specify a file on your file system. When using a file on file system, remember to add “file:/” to an absolute path; otherwise, Spring will treat it as a relative path even the value starts with “/”.

PropertyPlaceholderConfigurer also allows you to define some default values using the property “properties“. The following is an example of using the default values if the file defined by “locations” property does not exist. Please note setting “ignoreResourceNotFound” to true is necessary. If not set, the application will throw exception if the defined property does not exist even we’ve defined the default values.

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="ignoreResourceNotFound" value="true" />
  <property name="locations">
    <value>file:///etc/app/jdbc.properties</value>
  </property>
  <property name="properties">
    <props>
      <prop key="jdbc.driverClassName">com.mysql.jdbc.Driver</prop>
      <prop key="jdbc.url">jdbc:mysql://localhost:3306/mytechtip</prop>
      <prop key="jdbc.username">jdbc_username</prop>
      <prop key="jdbc.password">xxx</prop>
    </props>
  </property>
 
</bean>
 
<bean id="dataSource" destroy-method="close" 
    class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>
Jun
7
2010

How to Configure Spring beans.xml File: Collection properties and EntityManagerFactory Examples

Java beans in Spring can also have their collection properties populated in the beans.xml file. The collection properties here mean things like List, Map and Array.

For example, if you want to create a JPA EntityManagerFactory with a set of connection properties, these properties can be configured in beans.xml like this:

<?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="entityManagerFactoryCreator" 
    class="com.mytechtip.example.EntityManagerFactoryCreator">
    <property name="persistenceUnitName" value="HRMN_Repository"/>
    <property name="jpaProperties">
      <props>
        <prop key="openjpa.ConnectionURL">the_url</prop>
        <prop key="openjpa.ConnectionDriverName">the_driver_class_name</prop> 
        <prop key="openjpa.ConnectionUserName">the_user_name</prop>
        <prop key="openjpa.ConnectionPassword">the_password</prop>
      </props>
    </property>
  </bean>
</beans>

Here, jpaProperties in the actual java class “EntityManagerFactoryCreator” is an instance of Properties. And you can just use this properties to create EntityManagerFactory.

    // ...
    private Properties jpaProperties;
    //...
    public void setJpaProperties(Properties prop) {
        this.jpaProperties = prop;
    }
    // ...
    public EntityManagerFactory create() {
        return Persistence.createEntityManagerFactory("myPersistenceUnit", prop);
    }

Actually, Spring already have something similar for you to access EntityManagerFactory with ease. The beans used for the task are:

  • org.springframework.orm.jpa.LocalEntityManagerFactoryBean
  • org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean

More information / examples can be found here about the support of JPA entity manager factory creatation in Spring.

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.

Mar
24
2010

Remember to Clear Entity Manager if Entities No Longer Used

Recently  a lesson was learned about the proper use of Java JPA to persist a large number of records into database in a batch process.

Some times it is necessary to load the records line by line from a large file and insert into the database table. There can be several ways to do this:

  • Use the database provided tool to load the data into table. It can be a special sql command or a special stored procedure. This method is quite database specific and not portable.
  • Write the program to load the data into the database table (Using JDBC if the program is written in Java).  This method can be applied to different databases if the insert SQL statement conforms to a level of standard.
  • Use JPA to persist the object one by one. This allows for changing database more easily (under the condition that the JPA provider supports the database.

We used the third options to load the records into the database as we want to support multiple databases without  low level tweaking. However, the first implementation seemed very slow compared with the second option. And it became slower and slower when process of persisting records  progressed.

After a few checking, we realized that we didn’t call the method “clear” of the class EntityManager each time we persisted the object.  The EntityManager kept managing these objects so the resource was not released immediately, making it become slower and slower.

Once we add the “clear” method call, the performance became acceptable. So lesson learned about the use of JPA.

Nov
5
2009

Bad Request Error with apache mod_rewrite

If you use apache module mod_alias together with module mod_rewrite, you probably encounter “Bad Request” error if the settings are not correctly configured.


For example, if you want to make the folder “/opt/mysite_v1.2″ have the alias as “/mysite” so it can be accessed as http://www.mydomain.com/mysite. And you want to have clean url “/mysite/page1″ mapped to “/mysite/index.php?p=page1″.

To define the alias, just add the following in the httpd.conf file:

Alias /mysite/ “/opt/mysite_v1.2/”
<Directory “/opt/mysite_v1.2/”>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>

To allow clean URL. you need to have the following in the “.htaccess” file in the folder “/opt/mysite_v1.2″

RewriteEngine On
# Rewrite base
RewriteBase   /mysite

#  now the rewriting rules
RewriteRule   ^([0-9a-zA-Z_]+)$  index.php?p=$1

Please NOTE that “RewriteBase” Directive is very essential. Without it, you will get the well known “Bad Request” Error.

More information can be found in Apache mod_rewrite documentation.