DI in Java without annotations?

ぐ巨炮叔叔 提交于 2019-12-21 20:45:52

问题


Is there any way (existing framework) to configure DI in Java without having to add annotations to classes where they "don't belong"?

In my research, it looks like to accomplish constructor injection we need to add some annotation to the constructor, like this:

@Inject // or @Autowired for Spring Boot
public MyInjectedClass(IThing1 thing1, IThing2 thing2) { ... }

Spring Boot also suggests adding @Service to implementations in order to register them with DI for injection.

Adding these annotations brings DI into the injected class (MyInjectedClass and any controllers, service implementations, etc.). Those classes should have no concept of DI, they should just be given the things they ask for in the constructor and not care about how they got there.

I know you can use the @Configuration attribute in Spring Boot, but this still feels not very configurable or powerful. Is there any way to accomplish this using Java without annotations? E.g. like how SimpleInjector, AutoFac, etc. work in C#? (Configured via code, not XML or config files, and not via annotations.)

If not, I'm curious why such a different approach has been taken between Java and C# in regard to DI.

Update I've offended someone in the comments but that was not my intent at all. I am asking a legitimate question. Let me highlight my concern/question in another way.

Suppose I have the following packages/classes. I have marked each case where each type of DI will appear. By "appear" I mean these marked classes/packages have some relation to the DI framework being used.

[A]: annotation-based DI (3rd party package dependency)

[C]: configuration-based DI

  • data_access [A]

    • repositories
      • PersonRepository [A]
  • logic [A]

    • people
      • CreatePersonCommandHandler [A]
      • UpdatePersonCommandHandler [A]
  • services [A] [C]

    • controllers
      • PersonController [A] [C]

I hope this helps to illustrate my true question. The footprint of annotation-based DI extends into the far reaches of the stack, whereas configuration-based DI is only used in the outermost (entry) application, where the composition root lives.

来源:https://stackoverflow.com/questions/49557522/di-in-java-without-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!