Using Jersey's Dependency Injection in a Standalone application

前端 未结 2 682
清歌不尽
清歌不尽 2020-12-21 03:31

I have a interface here

interface Idemo{
  public int getDemo(int i);
}

And it\'s one implementation

class DemoImpl implem         


        
2条回答
  •  攒了一身酷
    2020-12-21 04:13

    I was facing the same situation but in the context of running some integrations test that needs to have some of the singletons that my application have already defined.

    The trick that I found is the following. You just need to create a normal test class or a standalone that use the DropwizardAppRule

    In my case, I use JUnit as I was writing some integration test.

    public class MyIntegrationTest{
    
     //CONFIG_PATH is just a string that reference to your yaml.file
     @ClassRule
        public static final DropwizardAppRule APP_RULE =
            new DropwizardAppRule<>(XXXApplication.class, CONFIG_PATH);
    
    }
    

    The @ClassRule will start your application like is said here . That means you will have access to everything and every object your application needs to start. In my case, I need to get access to a singleton for my service I do that using the @Inject annotation and the @Named

    public class MyIntegrationTest {
    
        @ClassRule
        public static final DropwizardAppRule APP_RULE =
            new DropwizardAppRule<>(XXXAplication.class, CONFIG_PATH);
    
        @Inject
        @Named("myService")
        private ServiceImpl myService;
    
    }
    

    Running this will set to null the service as @Inject is not working because we don't have at this point anything that put the beans into the references. There is where this method comes handy.

        @Before
        public void setup() {
    
    
            ServiceLocator serviceLocator =((ServletContainer)APP_RULE.getEnvironment().getJerseyServletContainer()).getApplicationHandler().getServiceLocator();
    
            //This line will take the beans from the locator and inject them in their 
            //reference, so each @Inject reference will be populated.
            serviceLocator.inject(this);
    
        }
    

    That will avoid creating other binders and configurations outside of the existing on your application.

    Reference to the ServiceLocator that DropwizardAppRule creates can be found here

提交回复
热议问题