Eclipse 4 Dependency Injection

Something else that’s completely new to me in Eclipse 4 is dependency injection (DI). This is used to prevent classes having to implement and extend other defined classes in order to provide the expected functionality of eg a View or a Handler. With DI you can write POJOs and still allow the Eclipse framework to execute the correct methods when certain actions are required. You can also ‘easily’ inject objects that remain persistent across classes within your application.

First Attempts

My early attempts at creating my own injectable objects weren’t too successful! I was trying to create a User object that would store information about the logged in user, allowing me to store their username, log them out after a certain period of inactivity, etc. Following Vogella’s tutorial I tried to create my User object in an addon using the following code:

public class UserAddon {
  @Inject
  public void createUser(IEclipseContext context) {
    ContextInjectionFactory.make(User.class, context);
 }
}

I also tried this:

public class UserAddon {
  @Inject
  public void createUser(IEclipseContext context) {
    User user = new User();
    context.set("user", user);
 }
}

But I could never access the same User object from other classes of my application. A new User object was always created, and any changes made to it were lost.

[GARD]

Success

I finally got this working after reading the forum post linked below. Tom Schindl suggests that objects of this nature should be stored in the MApplication context in order to make them available to all aspects of your application. His other top tip was to add the User object to the MApplication context using the FQN of the User object as the key value. This means a simple @Inject will inject the existing User object without having to use @Named(“key”) (possibly a point I was missing in my earlier attempts?)

public class UserAddon {

  @Inject
  public void createUser(MApplication application) {
    User user = new User();

    System.out.println("Username: "+user.getUsername()); //Default
    user.setUsername("Gareth");
    System.out.println("Username: "+user.getUsername()); //Gareth

    application.getContext().set(user.getClass().getName(), user);
  }	

}

So now to use the existing user object in another class:

public class LoginPart {

  @Inject
  private User user;

  public void someMethod() {
    System.out.println(user.getUsername); //Gareth
    user.setUsername("Fred");
    System.out.println(user.getUsername); //Fred
  }

}

Links

Vogella Eclipse 4 Tutorial – Injecting your own objects Forum discussion re sharing a data model in Eclipse 4

[GARD]


COMMENTS