Reputation: 66166
Suppose, we have 2 classes - Main
and MainDependency
. The second class is used only by Main
, and the purpose of using IoC is constructing an instance of Main
class.
MainDependency
class has a field of integer type. This field is not required to be set (or, let's assume it should always have a default value if nothing else is specified).
The problem: what's the most correct way to set the integer field? One way I see is creating similar field inside my Module
and then using that value inside configure
module. But I feel it's a wrong way.
Please, share your experience. Thx in advance.
Upvotes: 1
Views: 1243
Reputation: 15029
I think you mainly have two options:
1) Inject it using constant binding. The value of MY_CONSTANT
could be passed to Module
at instantiation time; could be taken from a system property, or maybe some other way.
class MainDependency{
@Inject
public MainDependency(@Named("myConst") int myConst){
//...
}
}
class Module extends AbstractModule{
public void configure(){
bindConstant().annotatedWith(Names.named("myConst").to(MY_CONSTANT);
}
}
2) Use assisted inject to create a factory which will take your value as a parameter and return an instance of MainDependency
:
interface MainDependencyFactory{
MainDependency create(int myConst);
}
class MainDependency{
@Inject
public MainDependency(@Assisted int myConst){
//..
}
}
class Module extends AbstractModule{
public void configure(){
bind(MainDependencyFactory.class).toProvider(
FactoryProvider.newFactory(MainDependencyFactory.class, MainDependency.class));
}
}
//to use the above, instantiate your factory (or inject it somewhere)
MainDependencyFactory f = injector.getInstance(MainDependencyFactory.class);
//Then you can create MainDependency with any value
MainDependency md = f.create(MY_CONSTANT);
Note that with assisted inject you don't need to implement MainDependencyFactory
. Guice will create it for you.
Upvotes: 2