Custom Dependency Injection, Simplified Spring-like Framework

Posted on Posted in Java, Website Design

I’m a Spring fan, but I decided not to use Spring in our recent project because I don’t want bulky jar files in our application but I wanted to have spring-like configuration. So, I’ve decided to write my own dependency injection code in less than 50 lines of code!!

To simplify dependency injection, I’ve taken out most of the advanced configuration features and keep the implementation to bare bones. In summary, the code only performs dependency injection to make your application configurable from external property files. The result is a small and lightweight dependency injection framework that makes your application configurable via property files.

Of course, short and simple means less features. Some of the caveats from this implementation includes:

  • Assumes parameters in your DI methods is String. You will need to convert the parameter to the appropriate datatype in your code.
  • Assumes your class for injection extends the base Injectable class
  • Dependency injection is done using property files.

Below the main method for dependency injection. But I’ve also attached a complete set of codes and example.

public Injectable get(String id) {
	try {
		id = id.trim();
		String objectClassName = configPersistence.getSetting(id + ".class");
		if (StringUtil.isEmpty(objectClassName))
			throw new ConfigurationException(
						"Cannot find object class for id ["+id+"].");
		Class objectClass = Class.forName(objectClassName);

		// create new object
		if (!Injectable.class.isAssignableFrom(objectClass))
			throw new ConfigurationException(objectClass.getName() +
					" is not an instance of Injectable.");
		Constructor cxr = objectClass.getConstructor(String.class);
		Injectable object =  cxr.newInstance(id);
		// add reference to this object factory
		Field factory = Injectable.class.getDeclaredField("factory");
		factory.setAccessible(true);
		factory.set(object, this);
		// let's populate the object's attributes
		Map<string, Object> attributes = configPersistence.findSettings(id);
		for (String key:attributes.keySet()) {
			// get the method name
			String methodName = key.substring(key.lastIndexOf(".")+1);
			// ignore class definition
			if ("class".equals(methodName)) continue;
			// find a setter method for this attribute
			try {
				Method method = objectClass.getMethod(methodName, String.class);
				method.invoke(object,(String)attributes.get(key));
			} catch (NoSuchMethodException nsme) {
				throw new ConfigurationException("Method ["+methodName+
				"] not found for class ["+objectClass.getSimpleName()+".]", nsme);
			} catch (IllegalArgumentException iae) {
				throw new ConfigurationException("Method ["+methodName+
				"] invalid for class ["+objectClass.getSimpleName()+"].",iae);
			} catch (Exception e) {
				throw new ConfigurationException("Failed to invoke ["+
				methodName+"] for class ["+objectClass.getSimpleName()+"].",e);
			}
			}
		return object;
	} catch (ConfigurationException ce) {
		throw ce;
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}

There are 2 dependency files needed in this example. They are merely helper classes to enforce the rules. You may remove / change them as you please. To keep this blog short, I’m attaching a sample program that includes the files needed. Just run “Sample” application and notice that values in the classes are initialized from the property file called “inject.properties”.

Download sample codes

Enjoy!




One thought on “Custom Dependency Injection, Simplified Spring-like Framework

  1. I would like to download and wanted to see your code , is there is ant way i can see the code.

    Thanks and regards,
    Vishnu

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.