ZNackasha
ZNackasha

Reputation: 1089

When does Base Class Injection happen in Micronaut

I am using inheritance with micronaut. I have an application the does something similar to the following

@Prototype
class ValueHolder {
    public void doSomthing();
}

@Prototype
class Base {
    @Inject
    ValueHolder value;

    Base() {
        // Does Something
    }

}

@Prototype
class Parent extends Base {

    Parent() {
         super()
         value.doSomthing(); // NullPointerException
    }
}

I would like to know why value is still null and if inheritance is an anti-pattern in micronaot.

Upvotes: 1

Views: 465

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

I would like to know why value is still null and if inheritance is an anti-pattern in micronaot.

Inheritance is not an anti-pattern in Micronaut.

The issue you are having doesn't really have anything to do with Micronaut. It has more to do with how objects are allocated. You are referencing value in the Parent constructor but it is impossible for value to have been initialized by then. The code that will initialize the value property can't execute until the Parent instance is initialized, but you are trying to reference value before that happens. You would see the same behavior if you leave Micronaut out of it and simply invoke new Parent();.

It is unclear what you need the value object to do when the Parent is being constructed but one option to consider is instead of this:

import io.micronaut.context.annotation.Prototype;

@Prototype
class Base {
    ValueHolder value;

    Base(ValueHolder value) {
        this.value = value;
    }

}
import io.micronaut.context.annotation.Prototype;

@Prototype
class Parent extends Base {

    Parent(ValueHolder value) {
        super(value);
        value.doSomthing(); // Not NullPointerException
    }
}

Upvotes: 1

Related Questions