我正在编写一个Java包来与发电机表交互,我正在使用Guice进行DI。该软件包将客户端公开给其用户,如下所示 -
// External client
public class Client {
DataManager manager;
public static Client getClient() {
return Guice.createInjector(new MyModule()).getInstance(Client.class);
}
}
// Manager class to interact with dynamo
public class DataManager {
AmazonDynamoDb amazonDynamoDb;
DynamoDbMapper dynamoDbMapper;
@Time // IMPORTANT - This is AOP style metric recording which records the amount of time taken to do a particular operation
public void addRecord();
public void deleteRecord();
...
}
// Class that represents an entry in the table
public class Data {
}
其中一个用例是在将客户端实例返回给此包的用户之前必须执行表检查。这基本上意味着我必须在我的代码中的某处调用initializeTable()函数。我的问题是我应该把这个逻辑放在哪里?
我最终做的是这个(在模块本身上执行注入,将在客户端#getClient()方法中向Guice注册) -
public class InitializingModule extends AbstractModule {
/**
* Perform injection on this instance so that the table initialization happens before any usable class is
* returned to the clients of this package.
*/
@Override
protected void configure() {
requestInjection(this);
}
/**
* Configure dynamoDB to check for and initialize the table.
*
* @param startupUtil
* @throws Exception
*/
@Inject
void configureDynamo(DynamoStartupUtil startupUtil) throws Exception {
startupUtil.initialize();
}
}
那么这个初始化逻辑应该去哪里,以免DI的原则被违反,类很容易测试?请注意,Guice尚不支持@PostConstruct。