如何在Spring或EE中重写Guice接口DI的Injector.getInjector().getInstance(Interface.class)。

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月24日 22:43:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64048873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定