View RSS Feed

Spring Framework

How to Write a BeanPostProcessing in Spring

Rate this Entry
by , 11-16-2011 at 04:28 PM (2899 Views)
In the previous tip we talked about special beans in Spring. One of the Springís special beans that I had mentioned was using the BeanPostProcessor interface in order to cut into the beanís life cycle and review or alter its configuration. In this tip, I will show you how to wire one. As mentioned in the previous tip I mentioned that the BeanPostProcessor provides two methods to alter the bean after it has been created and wired:

Java Code:
Object postProcessBeforeInitialization(Object bean, String name) throws BeansException;

Object postProcessAfterInitialization( Object bean, String name) throws BeansException;
The postProcessAfterInitialization() method cycles through all of the beanís properties, looking for those that are of type java.lang.String. For each String property, it passes it off to the convertAnsi() method, which translates the String into UTF-8 bytes. Finally, the property is changed to the converted text. Iím conscious that this breaks encapsulation, but this is for demonstration purposes
The postProcessBeforeInitialization() method is left purposefully unexciting; it simply returns the bean unaltered.

Java Code:
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class AnsiConvertor implements BeanPostProcessor {

	@Override
	public Object postProcessAfterInitialization(Object bean, String name)
			throws BeansException {
		Field[] fields = bean.getClass().getDeclaredFields();
		try {
			for (int i = 0; i < fields.length; i++) {
				if (fields[i].getType().equals(java.lang.String.class)) {
					fields[i].setAccessible(true);
					String original = (String) fields[i].get(bean);
					fields[i].set(bean, convertAnsi(original));
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String name)
			throws BeansException {
		return bean;
	}

	public String convertAnsi(String theString) {
		byte[] utfBytes;
		try {
			utfBytes = theString.getBytes("UTF-8");
		} catch (UnsupportedEncodingException uee) {
			uee.printStackTrace();
			return "";
		}
		return new String(utfBytes);
	}
}

Submit "How to Write a BeanPostProcessing in Spring" to Facebook Submit "How to Write a BeanPostProcessing in Spring" to Digg Submit "How to Write a BeanPostProcessing in Spring" to del.icio.us Submit "How to Write a BeanPostProcessing in Spring" to StumbleUpon Submit "How to Write a BeanPostProcessing in Spring" to Google

Comments