Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What about dependency injection in modern java - is Guice or spring still the de facto standard?


I only do Java on Android, but Dagger (https://square.github.io/dagger/) might be a nice lightweight alternative.


Dagger is definitely more appropriate for Android applications and was developed specifically to address the issues with using something like Guice on mobile. That said, I love Guice and use it exclusively as it has a superset of features and startup performance is irrelevant in my area.

As Christian Gruber from the development team put it:

Dagger is a joint effort by Square, Google, some individual contributors from other places such as Nextflix, and is descended conceptually from Guice - specifically from MiniGuice. It addresses some key challenges our users faced with Guice. From Square’s side (/u/swankjesse can clarify this) it was the need to get high-performance, low-startup dependency injection on Android. From our side, it was that and the desire to trim the API weight of dependency injection, to reduce the user confusion that comes from reflection and bytecode generation in stack traces and debugging environments, and to get early validation of your graph’s wiring.

Dagger is a substantial direction shift for Google, and we are investing time and resources in it. Guice will always have a superset of features compared to Dagger, though we do have projects using Dagger on the server and in stand-alone java apps. But Dagger is not as evolved in terms of the surrounding "scaffolding" code (servlet support, etc.) as Guice, and won’t be for quite some time. Additionally, some teams will need or want some advanced Guice features that will never make it in to Dagger. [1]

[1] http://www.reddit.com/r/java/comments/1y9e6t/ama_were_the_go...


I'll address that in part 3. Basically jsr330 is a good standard, and it's implemented by Guice, Dagger and Spring


If you're planning at least 3 parts, have you considered turning this tutorial into a Leanpub book? It's the perfect start to one... (Disclosure: I'm a Leanpub cofounder)


I don't know. I'll give it a try.


Cool. Let me know how it goes!


I try to avoid it as much as possible. It's confusing at least to me and makes maintaining code over a long haul an arduous dull process. I'm getting to the point where I prefer straight JDBC over Hibernate too. It takes longer to code but I've seen speed increases of several times over Hibernate in those situations. JDBC code is just linear but I feel it's easier to maintain in the long run.


Speed is not the only concern when it comes to JDBC vs ORM (JPA/Hibernate).

The more complex the data model, the more one needs to know the inner working of JPA. I've shared my struggle understanding how JPA works even for a medium-level complexity of the JPA entities.

Some of the problems I've encountered using JPA:

- The whole EntityManager act as L1 cache occasionally tripped me when writing Integration-Tests

- The relationship direction (owning, etc) can be confusing to learn

- Reference vs Lazy vs Eager load

Having said that, HBM2DDL is a nice tool that can work as maven plugin such that changes on the JPA entities can resulted the DDL to be updated properly thus maintaining consistency between Java Data Model and the DB schema.


I agree. Hibernate has become a downright liability at times in our codebase. These days I only use it in new code for query parameterization and result row transforms into models.

Speaking of which, if anyone knows of a good library for query parameterization alone, let me know...


JDBI is quite good: http://jdbi.org/


We use JDBI @Truecaller together with Metrics library. Not only it is clean and tidy, it also gives you immediate profiling around your database calls. This is priceless in a big service oriented environment. With it, you can exactly see the rate of happening (mean/last 1/5/15 minutes average) and latency (mean/avg/std-dev/75/95/98/99/99,9percentiles) for each database query. I wouldn't want to go back to manual logging and optimization hell. JDBI+Metrics opens a totally new dimension to your monitoring/profiling/optimization!


A second shoutout for JDBI. I don't attempt to use it for anything fancy, but it hides a lot of the JDBI boilerplate in a very sane way.


Cheers mate! That createQuery() call looks to be exactly what I need (query safety on a low level JDBC stream object).


Checkout Dalesbred, http://dalesbred.evident.fi/

It's our in-house jdbc library, and has IDEA plugin. We use it in many small projects, and in one major.


This might be of interest to you:

https://github.com/gilesjb/copalis.sql


Thankfully I am seeing more and more comments like this. I really think we off the deep end with all this. Simple is key.


Back in 2007 we had a developer pissing one architect as he replaced a few J2EE 1.3 entity beans by pure JDBC calls.

The modified code ran in a fraction of the time the pure architecture was running.


I agree... can't live without Dependency Injection (one of the reasons I refuse to move off of Java). I've been using CDI and TomEE for small simple stuff (it just works).

Can't stand Spring Framework anymore. It set out to replace the bloatware of Java EE 1.5 but it ended up becoming what it was meant to replace.


It occurs to me that dependency injection has this strange similarity to functional programming. I mean, clearly, you're playing with objects instead of functions, and they can have state, and so on, so it's not functional. But still, there's a similarity in how you're breaking things apart.

Spring: Maybe the problem is that Jave EE 1.5 was a reasonably good solution for the problems it was trying to solve? Maybe you can't do radically better and still actually solve the problems?


Genuinely curious : i've been playing with dependency injection, and really never got to understand the true use of it.

I mean, what's the point of being able to replace an implementation outside the source code itself ? You'd still have to extensively test the thing and recompile it...

Is there more to it than just being able to replace a class by its mock up, for unit testing ?


When you've got a complex graph of objects and dependencies between them, DI can easily take care of instantiating an A and feeding it to a B that requires an A and so on and so on.

In our projects we'll have a DebuggerFooImpl, a MockFooImpl, and a ProdFooImpl. Spring's AppConfig classes then can create the proper object at startup based on environment profiles and no consumers have to do any more than ask for the Foo object to be injected into them, isolating them from any environment awareness/coupling.

There are other benefits from DI as well, but the above at the low hanging fruit, isolating the complexity of object creation from the object's consuming classes.


I think the point is that you don't want to be instantiating (and thus configuring) a dependency at the site where it is used. The code in class Foo should be limited to implementing Foo, not instantiating and configuring its dependency Bar.


So why not just pass its dependency as a constructor argument?


Passing a dependency as a constructor argument is dependency injection:

http://en.wikipedia.org/wiki/Dependency_injection#Constructo...


Right, my point was more "why do you need a framework to call constructors for you?".


That's what IoC containers do, or via setter.

However a IoC container can automatically create, and send through the object based convention(IMessageQueue -> MappedTo -> MessageQueue) or configuration (IMessageQueue -> MappedTo -> APMQMessageQueue).


It tries to disentangle two different problems:

1. Does my class work appropriately? Does it encapsulate/hide/abstract the right behavior? Does it function correctly with other classes that implement certain inferfaces?

2. Is my network of classes correctly defined so that I can use them all together in a particular way?

http://programmers.stackexchange.com/questions/92393/what-do...


IMO dependency injection encourages making very deep object graphs. constructor argument passing can be cumbersome, but jumping into new code it is much more clear, and it encourages you to write flatter code structures. i go without.


It depends. One thing that I thought is an interesting feature of Spring, is that it allows the framework to inject code between your dependencies like decorators. This allows them to do aspect-oriented-programming transparently. And I think there's some interesting ideas here. For example, you can mark the interface of a class as @Transactional, and all your implementations will get the behavior.


I think that's the interception way of AOP? Unity IoC in c# also does this.

The IoC container will return transparent proxy(Not the original object), which then calls the underlying method(after doing the AOP behaviour).


Be careful of using these though.

I had an obscure bug using dynamic proxy (castle dynamic proxy2) a while ago in a WPF application. I was proxying to an interface so it created a proxy object in between that in the actual class so it was eating my C# event. Changing the proxying from an interface to a subclass fixed it.

Boy that was a fun one to figure out.


There are definitely more advantages than just the unit testing side. The Google IO talk on Guice does a pretty good job of explaining the benefits:

https://www.youtube.com/watch?v=hBVJbzAagfs


Not to sound snarky, but you should read any introduction to dependency injection. The benefits are generally covered very thoroughly, and what you said is not usually considered a benefit.


Wikipedia article on dependency injection, section titled "Advantages", _first_ bullet: "The result is more independent clients that are easier to unit test in isolation using stubs or mock objects that simulate other objects not under test."

Would you like to try again?


The OP said "I mean, what's the point of being able to replace an implementation outside the source code itself."

Where, in what you posted, does it reference being able to replace implementations outside of the source code itself?

Would you like to try again?


You should give the latest version a try. Spring implemented JavaConfig, which allows you to avoid XML altogether. Coupled with the ComponentScan annotation, it can't get any simpler.


What web framework can use that works with CDI, and standard EE stuff that is request-repoonse based?


My preference for DI is Declarative Services in OSGi. OSGi is a nice specification for creating modular Java systems.


i've seen a resurgence of 'new'




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: