Search code examples
javaguice

How to re-write Guice Interface DI Injector.getInjector().getInstance(Interface.class) on Spring or EE


Guice is avaliable for getting instance of Interface.class, But how we can get the same thing for Interface in Java EE or Spring?

TestVar testVar = Injector.getInjector().getInstance(Interface.class)

Solution

  • Using spring the IoC container is the ApplicationContext. You can directly request it like this.

    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    Interface myService = ctx.getBean(Interface.class);
    

    Or you can inject it to your component.

    Keep in mind this is a bad practice. You should never request the container directly. You should let it resolve dependencies for you.