Hacker News new | ask | show | jobs
by throwaway97135 1731 days ago
The code base at work has 100s of thousands of lines in several services based on Spring Boot. There's not a single factory in our code.

We also do not use XML to configure DI. Just add a annotation to a class and you can inject it automatically in any constructor without any additional config/annotations.

If this is too much "magic" for someone's taste, I will not argue even if I have a different view. But please do not make absolute statements based on a bad experience in some companies.

Modern Java and frameworks have evolved a lot in recent years.

1 comments

My take on this is that just injecting stuff in a constructor is an antipattern. Why not pass the data through methods instead of accessing it through a singleton in a constructor?

I understand the need for DI, sometimes the order of instantiation is necessary but for everything else I get lost in the DI constructor injection stuff.

There’s typically a separation between “services” and “data” in this style of app. Data is typically a request or some result obtained from another service such as the database. A service can have a lifetime distinct from the data, such as a database service that uses a connection pool, which is scoped to the lifetime of the application.

In a functional language you could use a reader or environment monad to abstract the dependencies, but you don’t have that ability in a language like Java (and it’s not worth torturing the language to do it because it’s not idiomatic). So DI in Java ends up constructor-injecting service dependencies and using the method parameters to declare data dependencies.

Edit: another benefit of DI is that it allows for multiple lifetime scopes beyond application and method call. Spring has request and transaction scopes, for instance. Managing all that in Java without DI is a nightmare.