Posts Tagged ‘di’
  • Spring can inject Servlets too!

    In this article, I will show you that Spring dependency injection mechanism is not restricted solely to Spring-managed beans, that is Spring can inject its beans in objects created by the new keywords, servlets instantiated in the servlet container, and pretty anything you like. Spring classical mode is to be an object factory. That is, Spring creates anything in your application, using the provided constructor. Yet, some of the objects you use are outer Spring’s perimeter. Two simple examples:

    • servlets are instantiated by the servlet container. As such, they cannot be injected out-of-the-box
    • some business objects are not parameterized in Spring but rather created by your own code with the new keyword

    Both these examples show you can’t delegate to Spring every object instantiation.

    There was a time when I foolishly thought Spring was a closed container. Either your beans were managed by Spring, or they didn’t: if they were, you could inject them with other Spring-managed beans. If they weren’t, tough luck! Well, this is dead wrong. Spring can inject its beans into pretty much anything provided you’re okay to use AOP.

    In order to do this, there are only 2 steps to take:

    Use AOP

    It is done in your Spring configuration file.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
      <This does the magic />
      <context:spring-configured />
      <-- These are for classical annotation configuration -->
      <context:annotation-config />
      <context:component-scan base-package="" />

    You need also configure which aspect engine to use to weave the compiled bytecode. In this cas, it is AspectJ, which is the AOP component used by Spring. Since i’m using Maven as my build tool of choice, this is easily done in my POM. Ant users will have to do it in their build.xml:

    <project xmlns=""

    Configure which object creation to intercept

    This is done with the @org.springframework.beans.factory.annotation.Configurable annotation on your injectable object.

    public class DomainObject {
      /** The object to be injected by Spring. */
      private Injectable injectable;
      public Injectable getInjectable() {
        return injectable;
      public void setInjectable(Injectable injectable) {
        this.injectable = injectable;

    Now with only these few lines of configuration (no code!), I’m able to inject Spring-managed beans into my domain object. I leave to you to implement the same with regular servlets (which are much harder to display as unit test).

    You can find the Maven project used for this article here. The unit test packaged shows the process described above.

    To go further:

  • Simplest Java decoupling without 3rd party frameworks

    "[...] coupling (or dependency) is the degree to which each program module relies on each one of the other modules."

    From Wikipedia

    In object-oriented programming, removing dependencies is done by using interface. Thus, if class A is dependent on class B, we introduce interface C, which is implemented by B. Now A depends on C  (see below).

    This first step in decoupling is called programming by interface. Anyway, we still have to “feed” class A with a C interface, be it a B object or whatever instance that implements C. So, we need an instance of such a class. In a standard code, B is instantiated by class A in this fashion:

    public class A {
        private C c = new B();

    Oh dear! It seems we introduced the dependency from A to B again… Hopefully, there are answers to this problem, namely Dependency injection. In dependency injection, an external module is responsible for instantiating and setting the object of class B. The code becomes the following:

    public class A {
        private C c;
        public void setC(C c) {
            this.c = c;

    Now, the dependency from A to B is removed. The DI framework creates a new B and pass it to the A object through the setter: it is the only component aware of (and thus dependent on) class B. Although DI is nowadays clearly mainstream, thanks largely to the Spring framework, there are other solutions to remove dependency. One such solution is the Service Locator core JEE pattern:

    In this diagram, the Client doesn’t reference the Target directly but gets it through an intermediary object called the Service Locator. This pattern is illustrated by the following code, which performs a JNDI lookup:

    public class ServiceLocator {
        /** Singleton. */
        private static ServiceLocator me;
        /** JNDI context to connect to. */
        private final InitialContext context;
        /** Objects cache. */
        private Map cache;
         * Gets an instance of the locator.
         * @return Singleton
         * @throws NamingException
        public static ServiceLocator getInstance() throws NamingException {
            if (me == null) {
                me = new ServiceLocator();
            return me;
        private ServiceLocator() throws NamingException {
            context = new InitialContext();
         * Get the object stored under the name in the JNDI tree. First look up in
         * the cache, then in the backing tree.
         * @param name
         * @return Object stored
         * @throws NamingException
        public Object lookup(String name) throws NamingException {
            Object object = cache.get(name);
            if (object == null) {
                object = context.lookup(name);
                cache.put(name, object);
            return object;

    Obviously, this locator is very simple and adopts the simplest of caching strategies; yet, it works.

    There’s another form of service locator that is not well known (read: only true geeks know about it) that is avalaible in JDK since Java 1.3: it is the Service Provider. This feature can be a life saver. It lets you, if you have cleanly separated JARs, one of interfaces (API) and one of implementations, to decouples your client code from the implementation altogether and use only the interfaces. How is it done?

    First, you have to have your code cleanly separate interface and implementations (see above). Then, for each interface, create a new file that will take place in your implementation JAR under META-INF/services. The name of the file should be the fully qualified name of the interface and the content of the file should be the fully qualified name of the chosen implementation. Last, in your code, you should only use the following snippet:


    That’s it, as long as you take care to put both interfaces and implementations JARs on the classpath. A word of warning though: if there’s more than one implementation on the classpath, the choice is not determined. Now you can astonish your fellow co-workers with this simple, yet powerful trick. If you know about OSGI, you can see that looks much like an embryo of OSGI service layer. The advantage of this solution is that you only need a JDK 1.3+. The drawback is that you can’t manage the lifecycle of your applications, it only provides services implementation.