Am I not allowed to use @Nullable with @Named?

935 views
Skip to first unread message

Michael Burton

unread,
Nov 20, 2009, 9:13:57 PM11/20/09
to google-guice
I'm injection a constant String into a provider to configure some
info, but I don't want the constant to be required. Thus I'd like to
make it @Nullable so that I can use a sensible default if one isn't
provided.


public class SharedPreferencesProvider implements
Provider<SharedPreferences> {
protected static final String DEFAULT = "default";

@Inject @Nullable @Named("sharedPreferencesContext") protected
String context;
@Inject protected Provider<Context> contextProvider;


public SharedPreferences get() {
return contextProvider.get().getSharedPreferences(context!
=null ? context : DEFAULT, Context.MODE_PRIVATE);
}
}


Seems pretty straightforward, but I keep running into the following
exception:


E/AndroidRuntime( 803): com.google.inject.CreationException: Guice
creation errors:
E/AndroidRuntime( 803):
E/AndroidRuntime( 803): 1) No implementation for java.lang.String
annotated with @com.google.inject.name.Named
(value=sharedPreferencesContext) was bound.
E/AndroidRuntime( 803): while locating java.lang.String annotated
with @com.google.inject.name.Named(value=sharedPreferencesContext)
E/AndroidRuntime( 803): for field at
roboguice.inject.SharedPreferencesProvider.context(Unknown Source)
E/AndroidRuntime( 803): at roboguice.config.AndroidModule.configure
(AndroidModule.java:52)
E/AndroidRuntime( 803):
E/AndroidRuntime( 803): 1 error
E/AndroidRuntime( 803): at
com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist
(Errors.java:354)
E/AndroidRuntime( 803): at
com.google.inject.InjectorBuilder.initializeStatically
(InjectorBuilder.java:152)
E/AndroidRuntime( 803): at com.google.inject.InjectorBuilder.build
(InjectorBuilder.java:105)
E/AndroidRuntime( 803): at com.google.inject.Guice.createInjector
(Guice.java:92)
...

Am I missing something?

Cheers,
Mike

limpb...@gmail.com

unread,
Nov 21, 2009, 2:18:17 AM11/21/09
to google-guice
I think you've mixed up nullable with optional. You probably want
this:
@Inject(optional=true) @Named("sharedPreferencesContext") protected
String context;

http://code.google.com/p/google-guice/wiki/Injections
http://code.google.com/p/google-guice/wiki/UseNullable

Michael Burton

unread,
Nov 21, 2009, 2:35:06 AM11/21/09
to google...@googlegroups.com
Ah yes, a distinction I wasn't aware of until just now. That fixed it, thanks!

Mike
> --
>
> You received this message because you are subscribed to the Google Groups "google-guice" group.
> To post to this group, send email to google...@googlegroups.com.
> To unsubscribe from this group, send email to google-guice...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/google-guice?hl=.
>
>

Reply all
Reply to author
Forward
0 new messages