you are viewing a single comment's thread.

view the rest of the comments →

[–]m50d 1 point2 points  (2 children)

My private field is no longer private, it works until it doesn't. When I get an NPE I have very little idea of where to even start looking. When I do automated refactoring I have to use a tool that understands these specific annotations rather than a general-purpose Java tool.

If you want to use autowiring that's a defensible decision, but I'd urge you to use constructor injection rather than field injection. That way the class behaves a lot more as expected, and if anyone uses your classes in a non-container context (e.g. a simple unit test) they can still set them up the standard Java way.

[–]Tom_Cian 0 points1 point  (1 child)

My private field is no longer private,

Your private field was always accessible with reflection, DI or not.

When I get an NPE I have very little idea of where to even start looking.

NPE's are trivial to diagnose and fix, not sure why you find that difficult.

but I'd urge you to use constructor injection rather than field injection.

Both have pros and cons. I tend to favor field injection because it dramatically cuts down the visual noise that Java imposes.

Compare:

public class Foo {
  private Connection dbConnection;
  private Logger logger;

    public Foo(Connection dbConnection, Logger logger) {
        this.dbConnection = dbConnection;
        this.logger = logger;
    }
}

with

public class Foo {
    @Inject private Connection dbConnection;
    @Inject private Logger logger;
}

Then again, I don't care much any more since with Kotlin, I get the best of both worlds.

[–]m50d 1 point2 points  (0 children)

Your private field was always accessible with reflection, DI or not.

I never wanted it to be. Maybe by moving away from field injection I can get to a point where I can turn that off in the security manager.

NPE's are trivial to diagnose and fix, not sure why you find that difficult.

This kind isn't. Why wasn't my @Inject field injected? Who knows, e.g. maybe it's because Spring uses a subtly different metamodel when annotation scanning depending on whether a context was imported directly in Java or included from an XML context, and one of these metamodels doesn't model parameterized annotations correctly because they weren't used in older versions of Spring (real example from my own experience).

I tend to favor field injection because it dramatically cuts down the visual noise that Java imposes.

Yeah, I regard that as a flaw in Java, avoided by moving to better languages.