Saturday, 25 August 2012

Spring IoC Container with Annotations (Standalone)

Spring's implementation of dependency injection and inversion of control is called the IoC container. Since version 3.0, it is possible to perform Java-based configuration instead of XML-based configuration using annotations.

Inversion of Control

Beans can be declared in classes annotated with @Configuration:
public class ConfigurationClass {

    private MyService myService = new MyService() {

        public long getData() {
            return System.currentTimeMillis();


    public MyService getMyService() {
        return myService;


public interface MyService {

    public long getData();

The above declares an implementation for the MyService interface.

Spring requires a special version of the application context to process annotations:
AnnotationConfigApplicationContext ctx =
    new AnnotationConfigApplicationContext();
After creating the application context, we scan all packages starting with com.jverstry for annotations. This detects the ConfigurationClass.

Dependency Injection

Other beans classes will want to use declared beans. For example:
public class MyServices {

    private MyService myService;

    public void setMyService(MyService myService) {
        this.myService = myService;

    public MyService getMyService() {
        return this.myService;

Using @AutoWired tells springs to inject the implementation of MyService in MyServices. This is detected in the package scanning too.
MyServices mcs = ctx.getBean(MyServices.class);
System.out.println("Data: " + mcs.getMyService().getData());
The above retrieves an instance of MyServices and calls the injected MyService. The generated output is:
Data: 1345873585387


Spring annotation processing requires the cglib dependency:
The above example is available from Github in the Spring-IoC-Container.

More Spring related posts here.