Wednesday, February 02, 2005

after a crazy attempt to do semi-fine grained layering of persistence, business logic, front-end friendly wrappers with spring i was puzzled on how to proceed creating unit tests that would work on all layers... each layer has its own applicationcontext.xml file aptly named applicationcontext-orm.xml, applicationcontext-manager.xml and applicationcontext-wrapper.xml... my utility class for loading the application context file could only accept a single string... calling it twice would result in spring only remembering the last applicationcontext invoked...

RTFM as always... and true enough (obviously) there is support for loading those context files contained in a string array... my crappy spring application context utility class ended looking like this:


/*
* Created on Aug 1, 2004
*
* Author Rogelio M. Nocom Jr.
*
*/
package com.mobileindie.spring;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;



/**
* @author nox
*
* based on Richard Hightowers article "orm without the container"
*
*/
public class ApplicationContextFactory {

// logger
private static Log log = LogFactory.getLog(ApplicationContextFactory.class);

// path and filename of application context
private static Object contextObject = null;

// make sure we are not loading twice...
private static int count = 0;

public static void init(String _contextObject) {
if (count >0) {
log.error("Can't initialize the application context twice: THIS SHOULD ONLY HAPPEN DURING TESTING");
}
contextObject = _contextObject;
count++;
}

public static void init(String[] _contextObject) {
if (count >0) {
log.error("Can't initialize the application context twice: THIS SHOULD ONLY HAPPEN DURING TESTING");
}
contextObject = _contextObject;
count++;
}

public static ApplicationContext getApplicationContext() {
if (contextObject == null) {
throw new IllegalStateException("Application context not initialized");
}
else if (contextObject instanceof String) {
String contextPath = (String) contextObject;
return new ClassPathXmlApplicationContext(contextPath);
}
else if (contextObject instanceof String[]) {
String[] contextPath = (String[]) contextObject;
return new ClassPathXmlApplicationContext(contextPath);
}
else {
throw new IllegalStateException("Context must be initialized via String or String[]");
}
}
}

No comments: