[英]How to call a method in a class after the application has been initalized?
I have classes as below.我有如下课程。 I want statements in constructor of DataService to be called itself after the application or DataService class has has been initialized and before DataHandler is intitalized.
我希望在应用程序或 DataService 类初始化之后和 DataHandler 初始化之前调用 DataService 构造函数中的语句本身。 But dataLoader object is null in the constructor.
但是 dataLoader 对象在构造函数中为空。 I am new to guice and want to know how can i achieve this using GUICE
我是 guice 的新手,想知道如何使用 GUICE 实现这一目标
@Singleton
@Managed
class DataService{
@Inject private DataLoader dataLoader;
DataService(){
dataLoader.load(); // I am trying to udnerstand why dataLoader is null?
}
}
@Singleton
@Managed
class DataHandler{
@EventHandler
public void handle(StaticData data){
//some logic om data
}
}
Class StaticDataModule extends AbstractModule{
@Override
protected void configure(){
bind(DataService.class).asEagerSingletin();
bind(DataHandler.class).asEarSingleton();
}
}
dataLoader
is null
because it is not yet initialized dataLoader
为null
因为它尚未初始化You request an injection of a field, yet you try to call it before it is even initialized.您请求注入一个字段,但您尝试在它被初始化之前调用它。
In order, what is executed?依次执行什么?
private double pi = 3.14;
private double pi = 3.14;
You have to understand that Guide is outside the constructor, even @Inject
.您必须了解 Guide 位于构造函数之外,甚至是
@Inject
。 When you instantiate an object, its constructor is first called, then the fields are injected.当您实例化一个对象时,首先调用其构造函数,然后注入字段。 It's like in Spring or in Java EE: the initialization is done using another method, annotated in
@PostConstruct
.这就像在 Spring 或 Java EE 中一样:初始化是使用另一种方法完成的,在
@PostConstruct
注释。 However Guide doesn't have such annotation.但是 Guide 没有这样的注释。
So the solutions to solve your problem are因此,解决您的问题的解决方案是
@PostConstruct
-like method that you created.@PostConstruct
的方法。 Example:例子:
Injector injector = Guice.createInjector(...);
DataService dataService = injector.getInstance(DataService.class);
dataService.init();
And your DataService
is as follows:您的
DataService
如下所示:
class DataService {
@Inject DataLoader loader;
void init() {
loader.load();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.