Dependency Injection in a Java 7 standalone application

Viewed 8699

I would like to use dependency injection in a large Java 7 standalone application, but I am not really sure where to start.

I have written a small test application:

public class Main {

    @Inject
    MyInterface myInterface;

    public static void main( String[] args ) {

        Main m = new Main();
        System.out.println(m.myInterface.getMessage());

    }

}

with an interface:

public interface MyInterface {

    String getMessage();

}

and an interface implementation:

@Singleton
public class MyInterfaceImpl implements MyInterface {

    public String getMessage() {
        return "Hello World!";
    }

}

The pom.xml contains one dependency:

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

This application compiles, but of course, it crashes with a NPE when trying to print the message. The injection has not happened.

So, my question are:

  1. Can dependency injection be achieved in a Java 7 standalone application?
  2. What other dependencies do I have to include to make it work?
  3. Does anyone have a simple operational example to share (I could not find any)?
1 Answers
Related