javadependency-injectionchecker-framework

Avoid 'uninitialized' errors on injected fields when using the Checker Framework


The Checker Framework's Nullness Checker generates an error when it encounters an uninitialised field.

[ERROR] /home/glts/src/example/src/main/java/BookRepositoryImpl.java:[39,7]
error: [initialization.fields.uninitialized] the constructor does not initialize fields: em

Now, it is a common pattern to have some fields injected via dependency injection:

@Repository
public class BookRepositoryImpl implements BookRepository {
    @PersistenceContext 
    private EntityManager em;

    @Override
    @Nullable
    public Book findById(int id) {
        return em.find(Book.class, id);
    }

    // ...
}

Here, the @javax.persistence.PersistenceContext annotation ensures that em will hold a reference to an EntityManager instance after the repository has been constructed.

More generally, in these cases the application framework guarantees that fields are initialised and non-null when they are used – but the Checker Framework can't know this.

So far, I've found that one remedy is to convert field injection to constructor injection (@Inject). This isn't an option in the above example, though.

Is there a way to tell the Checker Framework that a field is injected, and therefore properly initialised and non-null, without simply suppressing these errors?


Solution

    1. You can suppress the error for a single field by writing @SuppressWarnings("initialization.field.uninitialized") on the field declaration.
    2. You can suppress the error for all fields by writing @SuppressWarnings("initialization.field.uninitialized") on the class.

    There exist injection frameworks that can inject null as a value where a @PersistenceContext annotation exists, such as when the .xml file isn't present, the code isn't running in a transaction, etc. Writing the @SuppressWarnings("initialization.field.uninitialized") annotation is your way of saying that you trust that the one you are using will always inject a non-null value for your code.