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:
@Configuration
public class ConfigurationClass {

    private MyService myService = new MyService() {

        @Override
        public long getData() {
            return System.currentTimeMillis();
        }

    };

    @Bean
    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();
ctx.scan("com.jverstry");
ctx.refresh();
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:
@Component
public class MyServices {

    private MyService myService;

    @Autowired
    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

Dependencies

Spring annotation processing requires the cglib dependency:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>
The above example is available from Github in the Spring-IoC-Container.

More Spring related posts here.