Reputation: 1858
I have a simple class like so:
class MyClass {
private static SomeClass object = null;
public void init(Someclass injectedObject) {
object = injectedObject;
}
}
I init this class in my Guice module:
public class MyModule extends AbstractModule {
@Provides @Singleton
public SomeClass getStuff() {
SomeClass injectObject = new SomeClass();
MyClass.init(injectObject);
}
}
But when I package the my jar and submit it as a job to Flink runtime, I get an error saying NullPointerException: object in MyClass in null
I have even tried adding this to my method:
public static void main(String[] args) {
// Guice stuff
}
public void doStuff() {
MyClass.init(injectedObject);
}
Am I missing something? Why is an initialized variable getting reset to null in Flink runtime?
Upvotes: -1
Views: 147
Reputation:
There's a better way to inject into static fields using Guice:
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(SomeClass.class).in(Scopes.SINGLETON);
requestStaticInjection(MyClass.class);
}
}
class MyClass {
@Inject private static SomeClass object;
// no init method needed
}
However, it would be even better if you can omit the static
field altogether:
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(SomeClass.class).in(Scopes.SINGLETON);
bind(MyClass.class);
}
}
class MyClass {
private final SomeClass object;
@Inject
MyClass(SomeClass object) {
this.object = object;
}
}
Now you can request MyClass
instances either by injecting them or requesting them directly from the injector
, and they will all have access to the same SomeClass
instance.
Upvotes: 0