May 14, 2008

Loading Spring ApplicationContext in Class Path

Write a Startup Servlet and initialize it to 0 to load on application startup. Reading all ApplicationContext files from classpath to load them. The following example will explain how to load spring AppicationContext files while application startup. Following code write in Starup servlet.

private static final String[] CONTEXT_PATHS = {"/spring/applicationContext-*.xml" };
public void init(ServletConfig config) throws ServletException {
loadSpringResources(config);
}
private void loadSpringResources() {
ApplicationContext appContext = null;

// Set up the service locator factory...
BeanLocatorFactory.setApplicationContext(appContext);
// Start the different services.
}

Here Write the BeanLocatorFactory is as follows to set ApplicationContext and whenever your required.

public class BeanLocatorFactory {
private static ApplicationContext applicationContext = null;
private static final Map nameMap = Collections.synchronizedMap(new HashMap());

public static Object getService(Class interfaceClass) {
String cachedServiceName = (String) nameMap.get(interfaceClass);
if (cachedServiceName == null) {
int servicePackageLength = interfaceClass.getPackage().getName().length() + 1;
StringBuffer serviceName = new StringBuffer(interfaceClass.getName().substring(servicePackageLength));
cachedServiceName = serviceName.toString();
nameMap.put(interfaceClass, cachedServiceName);
}
return getService(cachedServiceName);
}
public static synchronized void setApplicationContext(ApplicationContext context) {
BeanLocatorFactory.applicationContext = context;
}
public static Object getService(String serviceName) {
try {
Object o = applicationContext.getBean(serviceName);
return o;
} catch (NoSuchBeanDefinitionException e) {
return null;
}
}
}