I would like to inject resource and use it in the constructor of singleton class with roboguice injection. Below is an example that shows what I need but injected field is null in the constructor. I was reading something about providers and overthink another special class for getting url but I am not so sure if it's convenient solution. Code below:
#Singleton
public class ProductService implements IProductService {
#InjectResource(R.string.server_url)
private String serverBaseUrl;
IProductAPI productAPI;
public ProductService() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(serverBaseUrl)
.build();
productAPI = restAdapter.create(IProductAPI.class);
}
public ProductDTO retrieveProductByEan(String productEan) throws RetrofitError {
return productAPI.getProductByEan(productEan);
}
}
As I can see reading the Roboguice documentation, Roboguice framework is only thought for Android programming. See the following link.
Injections are done when the super.onCreate() method is called in an Activity.
Here is a portion of code of a full example in github:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // #Inject, #InjectResource, and #InjectExtra injection happens during super.onCreate()
sayText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
// Have the remoteControl tell Astroboy to say something
remoteControl.say(textView.getText().toString());
textView.setText(null);
return true;
}
});
So I recommend to use a static value to refer serverBaseUrl.
Related
public abstract class MainService<T extends Managed> {
private static final Logger logger = LoggerFactory.getLogger(ContentService.class);
protected final ExecutorService executor;
private final boolean idValidation;
#Autowired
private LockValidator lockValidator;
public MainService() {
this(null, true);
}
public MainService(boolean idValidation) {
this(null, idValidation);
}
public MainService(final ThreadConfig tpConfig) {
this(tpConfig, true);
}
protected MainService(final ThreadConfig tpConfig, final boolean idValidation) {
// Some code
}
The code above works fine. But I have to replace the #Autowired annotation and inject the component via constructor. The problem is when I create this constructor:
public MainService(LockValidation lockValidation) {
this.lockValidation = lockValidation;
}
Instantly, these attributes get errors:
protected final ExecutorService executor;
private final boolean idValidation;
Variable 'executor' might not have been initialized
And of course, I guess that I need to send some parameters into the new constructor. The question is: How Could I refactor this code, using a constructor to inject the component instead of the annotation?
Quick fix:
public MainService(LockValidation lockValidation,ThreadConfig tpConfig,boolean idValidation) {
this(tpConfig,idValidation);
this.lockValidation = lockValidation;
}
You are not following SOLID principles (Dependency Injection) here by initializing executor inside the constructor. Best approach would be to use all argument constructor.
protected MainService(ThreadConfig tpConfig,boolean idValidation,ExecutorService executor,LockValidation lockValidation) {
this.tpConfig=tpConfig;
this.idValidation=idValidation;
this.executor=executor;
this.lockValidation=lockValidation;
/// Some code
}
Finally, I could see that to create a constructor could be a headache because it's probable to make refactors in the constructors. So, I decided to implement an injection via set method like this:
#Autowired
public void setLockValidation(LockValidation lockValidation) {
this.lockValidation = lockValidation;
}
It worked fine
I'm studying the MVVM to see if it can help me for my upcoming projects. What I understand so far, is that I need to use a ViewModel for holding my UI datas. I also need to use a Repository class to perform all my Requests to WebServices, and I'm using the Volley Library.
So here's what I did :
The ViewModel
public class MyViewModel extends ViewModel {
private MyRepository repository;
private MutableLiveData<MyPojo> pojo;
public MyViewModel(MyRepository repository) {
this.repository = repository;
this.pojo = new MutableLiveData<>();
}
public LiveData<MyPojo> updatePojo(){
pojo.postValue(repository.getPojo());
return pojo;
}
}
The Repository class
public class MyRepository {
private Application application;
private LiveData<MyPojo> pojo;
public MyRepository(Application application) {
this.application = application;
}
public MyPojo getPojo(){
if(pojo == null){
ApiRequest apiRequest = new ApiRequest(ApiSingleton.getInstance(application).getRequestQueue(), application);
apiRequest.apiGetRequest(ApiRequest.MY_ENDPOINT, null, new ApiRequest.apiCallback() {
#Override
public void onSuccess(Context context, JSONObject jsonObject) {
pojo = ApiResponseParser.parse(jsonObject, MyPojo.class);
}
#Override
public void onError(Context context, String message) {
}
});
}
return pojo;
}
}
It's specified here that a ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context. As you can see, I must use a context in order to perform a Volley request in my Repository class, and my ViewModel has a reference on this class.
Am I missing something in my design? Is Volley not compatible here?
Instead of passing the Application to your MyRepository's constructor and creating ApiRequest, you can pass the ApiRequest to MyRepository's constructor.
public MyRepository(ApiRequest apiRequest) {
this.apiRequest = apiRequest;
}
Now the MyRepository has no reference to Context.
And, regarding ViewModel having direct reference to MyRepository, you can do dependency inversion:
Create an interface, for instance, MyDataStore with the method getPojo(). MyRepository will implement this interface. While creating MyViewModel, you will pass the MyRepository to it, but MyViewModel will only have reference to MyDataStore.
interface MyDataStore {
... getPojo()
}
public class MyRepository implements MyDataStore {
...
}
public MyViewModel(MyDataStore dataStore) {
this.dataStore = dataStore;
this.pojo = new MutableLiveData<>();
}
The LifeCycle library provides the AndroidViewModel component, which is just an Application's context aware ViewModel, pretty close to Bob's answer, and did the job here without memory leaks hazards.
I've implemented a JAX-RS server application using Jersey 2.24.
I use the Guice-HK2 bridge so that the controller classes (those annotated with #Path) are injected with dependencies from Guice, not Jersey/HK2.
However, HK2 still creates instances of the #Path annotated classes itself.
Is there a way I can plug into Jersey/HK2 so that I'm notified when a #Path annotated class is created? Like some sort of lifecycle listener? Every time a #Path annotated class is created by Jersey/HK2 I want to do some registering/logging of that class.
If Guice were doing the actual creation of the #Path annotated class I think I could do it using a generic Provider but that's not available in this case, since Jersey/HK2 is creating the actual instance.
Thank you!!
I think the least intrusive way would be to just use AOP. HK2 offers AOP. What you can do is create a ConstructorInterceptor. Something like
public class LoggingConstructorInterceptor implements ConstructorInterceptor {
private static final Logger LOG
= Logger.getLogger(LoggingConstructorInterceptor.class.getName());
#Override
public Object construct(ConstructorInvocation invocation) throws Throwable {
Constructor ctor = invocation.getConstructor();
LOG.log(Level.INFO, "Creating: {0}", ctor.getDeclaringClass().getName());
// returned instance from constructor invocation.
Object instance = invocation.proceed();
LOG.log(Level.INFO, "Created Instance: {0}", instance.toString());
return instance;
}
}
Then create a InterceptorService to only use the interceptor for classes annotated with #Path
public class PathInterceptionService implements InterceptionService {
private static final ConstructorInterceptor CTOR_INTERCEPTOR
= new LoggingConstructorInterceptor();
private final static List<ConstructorInterceptor> CTOR_LIST
= Collections.singletonList(CTOR_INTERCEPTOR);
#Override
public Filter getDescriptorFilter() {
return BuilderHelper.allFilter();
}
#Override
public List<MethodInterceptor> getMethodInterceptors(Method method) {
return null;
}
#Override
public List<ConstructorInterceptor> getConstructorInterceptors(Constructor<?> ctor) {
if (ctor.getDeclaringClass().isAnnotationPresent(Path.class)) {
return CTOR_LIST;
}
return null;
}
}
Then just register the InterceptionService and ConstructorInterceptor with the DI system
new ResourceConfig()
.register(new AbstractBinder(){
#Override
public void configure() {
bind(PathInterceptionService.class)
.to(InterceptionService.class)
.in(Singleton.class);
bind(LoggingConstructorInterceptor.class)
.to(ConstructorInterceptor.class)
.in(Singleton.class);
}
});
See complete example in this Gist
See Also:
HK2 documentation on AOP
I'm trying for first time dagger and, after configuring the module, I get an error I don't understand.
My code is:
public class Parrot {
private Language language;
#Inject
public Parrot(Language language) {
this.language = language;
}
public void sayHello() {
System.out.println(language.getSalute());
}
}
public interface Language {
public String getSalute();
}
public class EnglishLanguage implements Language {
#Override
public String getSalute() {
return "Hello!";
}
}
My module is
#Module(
injects = Language.class
)
public class PetShopModule {
#Provides Parrot provideParrot(Parrot parrot){
return parrot;
}
}
And in the code I use it this way
EnglishLanguage lang=SystemApp.getSystemLanguage();
ObjectGraph objectGraph = ObjectGraph.create(new PetShopModule());
objectGraph.inject(myLanguage);
Parrot parrot = objectGraph.get(Parrot.class);
The compiler complains with:
error: com.example.petshop.Language could not be bound
with key com.example.petshop.Language required by com.example.petshop.PetShopModule
for com.example.petshop.PetShopModule
What do I am doing wrong?
Note: This is only a simplified example, in the real code the EnglishLanguage is a system class, and I can't modify nor create it, just get a reference
Instead of commenting on what you're doing wrong, let's give the correct example, and explain what's happening there.
This snippet is perfect, and stays as it is:
public class Parrot {
private Language language;
#Inject
public Parrot(Language language) {
this.language = language;
}
public void sayHello() {
System.out.println(language.getSalute());
}
}
public interface Language {
public String getSalute();
}
public class EnglishLanguage implements Language {
#Override
public String getSalute() {
return "Hello!";
}
}
With the #Inject annotation on the Parrot constructor, you're telling Dagger, "Whenever I request an instance of Parrot, use this constructor to instantiate it".
Dagger sees that Parrot needs an instance of the Language interface, and tries to find a way to retrieve it. However, since Language is an interface, Dagger needs to know which concrete type to use.
Since you cannot edit the EnglishLanguage class, you'll need to write a #Provider method for it:
#Module
public class PetshopModule {
#Provides
Language provideLanguage() {
return SystemApp.getSystemLanguage();
}
}
Now, you should be able to get an instance of Parrot out of your ObjectGraph, like this:
ObjectGraph graph = ObjectGraph.create(new PetshopModule());
Parrot parrot = graph.get(Parrot.class);
I have not tested this, bit this should work.
If you were able to modify the EnglishLanguage class, you could do the following. Annotate the EnglishLanguage constructor with #Inject, and request an EnglishLanguage instance in the Language provider method:
public class EnglishLanguage implements Language {
#Inject
public EnglishLanguage() {
}
#Override
public String getSalute() {
return "Hello!";
}
}
#Module
public class PetshopModule {
#Provides
Language provideLanguage(EnglishLanguage language) {
return language;
}
}
In this case, Dagger looks for the Language provider method, and instantiates an EnglishLanguage to return.
The existing answer is perfect, but didn't solve my obscure case.
If you have a base Activity with a couple of DI helper classes, make sure your Activity that extends this does so properly!
Base Activity class:
private fun initializeObjectGraph() {
activityObjectGraph = (application as App).getObjectGraph()
.plus(ActivityModule(this))
.plus(*getAdditionalModulesForObjectGraph())
}
protected open fun getAdditionalModulesForObjectGraph() = arrayOf<Any>()
abstract fun injectDependencies(activityObjectGraph: ObjectGraph): LifecycleReceiver
Overrides needed in extension Activity:
override fun injectDependencies(activityObjectGraph: ObjectGraph): LifecycleReceiver {
activityObjectGraph.plus(MyModule(this)).inject(this)
return DummyLifecycleReceiver
}
override fun getAdditionalModulesForObjectGraph(): Array<Any> = arrayOf(MyModule(this))
I would like to be able to change the Guice injections at runtime to support multiple injections based on user input. This is what I would like to achieve:
public interface IDao {
public int someMethod();
}
public class DaoEarth implements IDao {
#Override
public int someMethod(){ ... }
}
public class DaoMars implements IDao {
#Override
public int someMethod(){ ... }
}
public class MyClass {
#Inject
private IDao myDao;
public int myMethod(String domain) {
//If Domain == Earth, myDao should be of the type DaoEarth
//If Domain == DaoMars, myDao should be of the type DaoMars
}
}
I was thinking of writing my own Provider, but I don't know how to use that provider to change my bindings at runtime. Any input is welcome and appreciated :)!
Update
Here's what I currently came up with, it's not as pretty as I'd like, so I'm still looking for feedback
public class DomainProvider {
#Inject #Earth
private IDaoProvider earthDaoProvider;
#Inject #Mars
private IDaoProvider marsDaoProvider;
public IDaoProvider get(Domain domain){
switch (domain){
case EARTH:
return earthDaoProvider;
case MARS:
return marsDaoProvider;
}
}
public IDaoProvider get(String domain){
Domain parsedDomain = Domain.valueOf(domain.toUpperCase());
return get(parsedDomain);
}
}
//MarsDaoProvider would be equivalent
public class EarthDaoProvider implements IDaoProvider {
#Inject #Earth
private IDao earthDao;
public IDao getDao() {
return earthDao;
}
}
// This means that in "MyClass", I can do:
public class MyClass {
#Inject
private DomainProvider domainProvider;
public int myMethod(String domain) {
IDaoProvider daoProvider = domainProvider.get(domain);
IDao dao = daoProvider.getDao();
//Now "dao" will be of the correct type based on the domain
}
}
//Of course elsewhere I have the bindings set like
bind(IDao.class).annotatedWith(Earth.class).to(EarthDao.class);
Your version is almost perfect as it is: You're going to need to inject some kind of object that returns one or the other based on code you write, and don't need assisted injection or anything like that. That said, you can skip some of the boilerplate:
public class DomainProvider {
// Just inject Providers directly without binding them explicitly.
#Inject #Earth Provider<IDao> earthDaoProvider;
#Inject #Mars Provider<IDao> marsDaoProvider;
public Provider<IDao> get(Domain domain){
switch (domain){
case EARTH:
return earthDaoProvider;
case MARS:
return marsDaoProvider;
}
}
public Provider<IDao> get(String domain){
Domain parsedDomain = Domain.valueOf(domain.toUpperCase());
return get(parsedDomain);
}
}
Your MyClass in that case would be exactly identical. Here, Provider is either the one-method generic interface com.google.inject.Provider, or the equivalent builtin javax.inject.Provider that it extends. Read more about Guice Providers on the relevant Guice wiki topic.
bind(IDao.class).annotatedWith(Earth.class).to(EarthDao.class);
// You can now inject "#Earth IDao" and also "#Earth Provider<IDao>".
Basically, if you bind a key Foo (to a class, provider, #Provides method, or instance), you automatically get to inject either a Foo or Provider<Foo> with no additional work. Providers are also a great way to ensure that you get a new instance with every call to get, if that's what you want; with your original, you'll always get the same instance of EarthDao or MarsDao for any given DomainProvider you inject. (If you have a scoped binding like #Singleton, Guice will respect that too; Provider just lets Guice get involved, rather than reusing a plain old Java reference.)
This means you can skip your custom EarthDaoProvider and MarsDaoProvider, unless you really need to perform any external initialization on them—at which point you'd probably be better off calling bind(EarthDao.class).toProvider(EarthDaoProvider.class) so the preparation also happens when injecting EarthDao directly. You could also just have DomainProvider return an IDao instance directly by calling get on the appropriate Provider, and be assured that it'll be a new instance every time.