title: Jersey HK2 injection in manually created objects
body: <p>Is there any way to inject dependencies into manually created objects?</p>
  
  <pre><code>public class MyCommand {
      @Inject Repository repository;
  }
  
  public Repository {
      @Inject EntityManager em;
  }
  
  MyCommand command = new MyCommand();
  </code></pre>
  
  <p>Repository is properly registered the jersey ResourceConfig and can be injected in objects that are created through the CDI container for example a resource class.</p>
  
  <p>But since I create the Command myself the @Inject annotation gets ignored.</p>
  
  <p>Is there a way to get a registered class beside @Inject and @Context?
  Something like Application.get(Repository.class)</p>
  
  <pre><code>public class MyCommand {
      Repository repository;
  
      public MyCommand() {
          repository = Application.get(Repository.class);
      }
  }
  </code></pre>
  
  <p><strong>----- EDIT -----</strong></p>
  
  <p>Thanks to your help and some rethinking I found a solution for my problem.</p>
  
  <p>The first thing is that it's possible to inject the ServiceLocator without any preperation into you objects.</p>
  
  <p>The second thing is that I moved from normal commands with a execute method to a a command bus system.
  The reason for that is I have no controle over the creation of commands so there clean way to get dependencies injected.</p>
  
  <p>The new approach looks like this:</p>
  
  <pre><code>class CommandBus {
      private final ServiceLocator serviceLocator;
  
      @Inject
      public CommandBus(ServiceLocator serviceLocator) {
          this.serviceLocator = serviceLocator;
      }
  
      public void dispatch(Command command) {
          Class handlerClass = findHandlerClassForCommand(command);
          CommandHandler handler = (CommandHandler) serviceLocator.getService(handlerClass);
          handler.handle(command);
      }
  }
  
  interface CommandHandler {
      void handle(Command command);
  }
  
  interface Command {
  }
  
  class ConcreteCommand implements Command {
      // I'm just a dto with getters and setters
  }
  
  class ConcreteHandler implements CommandHandler {
      private final SomeDependency dependency;
  
      @Inject
      public ConcreteHandler(SomeDependency dependency) {
          this.dependency = dependency;
      }
      @Override
      public void handle(ConcreteCommand command) {
          // do some things
      }
  }
  </code></pre>
  
  <p>And in my resources I have something like this:</p>
  
  <pre><code>@Path("/some-resource")
  class Resource {
  
      @Context
      private CommandBus bus;
  
      @POST
      @Consumes(MediaType.APPLICATION_JSON)
      public void runCommand(ConcreteCommand command) {
          bus.dispatch(command);
      }
  }
  </code></pre>