Thursday, September 18, 2008

[Spring 2.5] How to use injection in your web application.

If you want to utilize from the latest Spring injection features, here's how to enable spring in your classes.
The example below is just written from memory and has not been verified compile wise, etc. If you find something strange, please comment. :)


Start out by adding the Spring Listener to your web.xml:

   org.springframework.web.context.ContextLoaderListener


Now add an applicationContext.xml to the WEB-INF/ directory containing:



 
 


context:component-scan will tell spring to scan the "base-package" for spring injection.
Change "com.maaloe.test" to the root package of where the classes using spring are located.
context:annotation-config will enable spring annotations.


To make your classes compile, add the following to your pom.xml (or include the spring jars in your classpath if you still haven't seen the light).


   org.springframework
   spring
   2.5.1


   org.springframework
   spring-test
   2.5.1



That's it, you should now be able to use spring injection in your classes. First, the interface of the "service" class that contains the logic you wish to inject:
public interface MyServiceLogic {
   public void doLogic(Object someObject);
}


Now, the class implementing the actual logic:
import org.springframework.stereotype.Component;

@Component
public class MyServiceLogicImpl implements MyServiceLogic {
   public void doLogic(Object someObject) {
      // Do whatever you want your "service" to do.
   }
}

Use @Component to tell spring that this class uses injection. Several other annotations exist depending on the situation, such as @Service, @Repository.


Now, inject the MyServiceLogic instance in your class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyWebApplication {
   private MyServiceLogic serviceLogic;
   
   @Autowired
   public void setMyServiceLogic(MyServiceLogic serviceLogic) {
    this.serviceLogic = serviceLogic;
   }

   public void myApplicationMethod() {
      Object myObject = ....
      
      // Now you can use the serviceLogic object
      // as Spring makes sure that it's initialized.
      serviceLogic.doLogic(myObject);
   }
}

Again, @Component is used to enable injection, in this case via @AutoWire.
@AutoWire will tell spring to inject an implementation of the interface MyServiceLogic in the setMyServiceLogic() method.
This will only work if you just have one implementation of the MyServiceLogic interface. If you have several implementations, use: @Qualifier("beanId") where you inject the implementation to give Spring a hint on what class to inject.

If you want to test your classes containing Spring injections, check this

No comments: