简体   繁体   中英

What is proper way to create objects inside method using Guice

What is proper way to create objects inside method of a Singleton object using Guice.

If I have some code like this below, what is a proper way to create instances of Class2? Class1 is singleton and need to create one new instance of Class2 everytime search is called (so I can not inject it with constructor field...) I will reorganize code if needed.

@Singleton
final class Class1 {

@Inject
private Class1(...){...}

public Class2 search(...){
   Class2 newInstance=...
   return newInstance;
}

}

I guess I found it. Need to use providers for such instances. Obtain class provider in constructor and use provider.get to obtain instances.

Something like:

@Singleton
final class Class1 {

Provider<Class2> p;

@Inject
private Class1(Provider<Class2> pParam;...){
p=pParam;
...
}

public Class2 search(...){
   Class2 newInstance=p.get();
   return newInstance;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM