英文:
How to re-write Guice Interface DI Injector.getInjector().getInstance(Interface.class) on Spring or EE
问题
Guice 可用于获取 Interface.class 的实例,
但是在 Java EE 或 Spring 中,我们如何获得同样的 Interface 实例?
TestVar testVar = Injector.getInjector().getInstance(Interface.class)
英文:
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)
答案1
得分: 0
使用Spring,IoC容器是ApplicationContext。您可以直接像这样请求它。
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Interface myService = ctx.getBean(Interface.class);
或者您可以将它注入到您的组件中。
请记住,这是一种不良实践。您不应直接请求容器。您应该让容器为您解析依赖关系。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论