Resolve named dependency with Dagger 2 after the class is initialized - java

I am using Dagger 2 for the dependency management of my Java application.
I have the following structure:
public interface SecondaryService
{
void doSomethingElse(String data);
}
public class SecondaryServiceFirstImpl implements SecondaryService
{
public void doSomethingElse(String data)
{
// Do something else
}
}
public class SecondaryServiceSecondImpl implements SecondaryService
{
public void doSomethingElse(String data)
{
// Do something else
}
}
public interface MainInterface
{
void doSomething(String data);
}
public class MainService implements MainInterface
{
private SecondaryService secondaryService;
private DatabaseService databaseService;
public MainService(SecondaryService secondaryService, DatabaseService databaseService)
{
this.secondaryService = secondaryService;
this.databaseService = databaseService;
}
public void doSomething(String data)
{
String name = databaseService.getName(data);
// Resolve the NAMED SecondaryService based on the name property and
// use the implementation.
}
}
And here is the Dagger Module code:
#Module
public class DependencyRegisterModule
{
#Provides #Named('first')
SecondaryService provideSecondaryServiceFirstImpl ()
{
return new SecondaryServiceFirstImpl ();
}
#Provides #Named('second')
SecondaryService provideSecondaryServiceSecondImpl ()
{
return new SecondaryServiceSecondImpl ();
}
#Provides
DatabaseService provideDatabaseService ()
{
return new DatabaseServiceImpl();
}
#Provides
MainInterface provideMainInterface(SecondaryService secondaryService, DatabaseService databaseService)
{
return new MainService (secondaryService, );
}
}
As you can see I have a SecondaryService interface that is implemented by two classes. I want to resolve the named dependency for the SecondaryService based on a parameter, that I get from the database inside a method in the MainService.
Is there a way to do this? If this does not work with a Named dependencies, is there another way to do this?
So far I have used a factory pattern, but it is very hard to manage, as I have to pass the dependencies of the classes inside their constructor.

#Named—or #Qualifiers in general—are intended to be used if you need 2 objects of the same kind, e.g. injecting a String username and String email. In this case a qualifier could be used to distinguish between those objects.
In your case it seems that you want either one object or the other. In your case you should use different modules if you want to take a clean approach, or add an if/else to your module in the constructor.
Use a base class
#Module
public abstract class ServiceModule {
#Provides
public abstract SecondaryService providesServcie();
}
Then just create 2 sub classes of this module and provide the needed service respectively.
When creating your component just supply the right implementation of your module
if(1 == 1)
new MyComponent.Builder().add(new OneServiceModule()).build();
else
new MyComponent.Builder().add(new OtherServiceModule()).build();
And remember, you don't have to duplicate your other #Provides methods, since you can just use multiple modules with the component.
Use an if/else construct
#Module
public class DependencyRegisterModule
{
private int whichModule;
public DependencyRegisterModule(int whichModule) {
this.whichModule = whichModule;
}
#Provides
SecondaryService provideSecondaryServiceSecondImpl ()
{
return whichModule == 1 ? new SecondaryServiceSecondImpl() : new SecondaryServiceFirstImpl();
}
}
I hope I don't have to explain how if/else works ;)

Related

Dagger2 - Insert value in #Module without using constructor

Following CodingInFlow's video tutorials on Dagger, I've reached the point where I'm seeing the use of #BindsInstance inside a #Component.Builder.
Having the following classes:
Model class:
public class DieselEngine implements Engine {
private static final String TAG = "Car";
private int horsePower;
#Inject
public DieselEngine(int horsePower) {
this.horsePower = horsePower;
}
#Override
public void start() {
Log.d(TAG, "Diesel engine started. Horsepower = " + horsePower);
}
}
the Modules:
#Module
public class DieselEngineModule {
private int horsePower;
//
// public DieselEngineModule() {
//
// }
//
// #Provides
// int provideHorsePower(#Named("dieselParam") int horsePower) {
// return horsePower;
// }
public DieselEngineModule(int horsePower) {
this.horsePower = horsePower;
}
#Provides
int provideHorsePower(int horsePower) {
return horsePower;
}
// We no longer need to manually instantiate DieselEngine obj using "new DieselEngine(horsePower)".
// Because we created a "provideHorsePower()" method, and we #Inject-ed the constructor of
// DieselEngine "DieselEngine(int horsePower){..}" so that the provideHorsePower() can inject into it.
#Provides
Engine provideEngine(DieselEngine dieselEngine) {
return dieselEngine;
}
}
public abstract class PetrolEngineModule {
// #Provides
// Engine provideEngine(PetrolEngine engine) {
// return engine;
// }
#Binds
abstract Engine bindEngine(PetrolEngine engine);
// NOTE: abstract methods are never instantiated, so we can't use normal #Provides methods, only static #Provides methods
}
the Component:
#Component(modules = {
WheelsModule.class,
DieselEngineModule.class,
})
public interface CarComponent {
Car getCar();
// Dagger 2 does not inject fields automatically. It can also not inject private fields.
// If you want to use field injection you have to define a method in your #Component interface
// which takes the instance into which you would like Dagger 2 to inject an object into this field.
// ex: all fields with #Inject from MainActivity will be injected once this method is used.
void inject(MainActivity mainActivity);
#Component.Builder
interface Builder {
#BindsInstance
Builder horsePower(#Named("horse power") int horsePower);
#BindsInstance
Builder engineCapacity(#Named("engine capacity")int engineCapacity);
#BindsInstance
Builder moduleParam(#Named("dieselParam")int someNumber);
// Builder dieselEngineModule(DieselEngineModule dem);
// dagger will automaticaly implement this method, we just have to declare it, because
// we are overwriting the builder definition
CarComponent build();
}
}
My question is: is there any way to "inject" a variable inside the PetrolEngineModule, in order to store it there, without having to add a parameter to the constructor of the module (see the commented method in the component) ?
for example: int a; inside PetrolEngineModule, which would be injected by the #Named("dieselParam") integer from the component. So that it would be set only once, when the Module is created for the first time.
I've experimented with the commented method in the DieselEngineModule, where the #Named variable is directly provided from the Component, in order to be used when providing the DieselEngine. But is that okay? I could use some advice here. Is that what I want to do? Use the #Named variable from the Component/Dependency Graph instead of storing it in the Module?

Defining bean with two possible implementations

So far, I had a very simple bean definition that looked like this:
#Bean
#Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return new ImplementationOne();
}
However, I now have situation where additional implementation class has been added, let's call it ImplementationTwo, which needs to be used instead of ImplementationOne when the option is enabled in configuration file.
So what I need is something like this:
#Bean
#Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return context.getEnvironment().getProperty("optionEnabled") ? new
ImplementationOne() : new ImplementationTwo();
}
Basically a way to instantiate correct implementation at bean definition time based on the configuration value. Is this possible and can anyone please provide an example? Thanks
It is possible to implement this without using #Conditional.
Assuming you have a Interface SomeInterface and two implementations ImplOne ImplTwo:
SomeInterface.java
public interface SomeInterface {
void someMethod();
}
ImplOne.java
public class ImplOne implements SomeInterface{
#Override
public void someMethod() {
// do something
}
}
ImplTwo.java
public class ImplTwo implements SomeInterface{
#Override
public void someMethod() {
// do something else
}
}
Then you can control which implementation is used in a configuration class like this:
MyConfig.java
#Configuration
public class MyConfig {
#Autowired
private ApplicationContext context;
#Bean
public SomeInterface someInterface() {
if (this.context.getEnvironment().getProperty("implementation") != null) {
return new ImplementationOne();
} else {
return new ImplementationTwo();
}
}
}
Make sure that the component scan of spring finds MyConfig. Then you can use #Autowired to inject the right implementation anywhere else in your code.
I think you are doing it wrong.
You should use #Conditional() on your implementation and not on your Interface.
Here is how I would do it :
The interface you will use on your code.
MyInterface.java
public interface MyInterface {
void myMethod();
}
The first implementation :
MyInterfaceImplOne.java
#Bean
#Conditional(MyInterfaceImplOneCondition.class)
public class MyInterfaceImplOne implements MyInterface {
void myMethod(){
// dosmthg
}
}
MyInterfaceImplOneCondition.java
public class MyInterfaceImplOneCondition implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("optionEnabled")
}
}
And for the 2nd implementation :
MyInterfaceImplTwo.java
#Bean
#Conditional(MyInterfaceImplTwoCondition.class)
public class MyInterfaceImplTwo implements MyInterface {
void myMethod(){
// dosmthg 2
}
}
MyInterfaceImplTwoCondition.java
public class MyInterfaceImplTwoCondition implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !context.getEnvironment().getProperty("optionEnabled")
}
}
In that case, you now just have to call the interface, and Spring will inject the bean corresponding to the right condition.
Hope it is what you are looking for, and I was clear enough!

Singleton scope throwing error in dagger 2

I have a pojo, decorated with Dagger 2's #Singleton annotation
#Singleton
public class CommonDataSingleton {
private String authToken;
private boolean isAuthenticated;
}
I have to inject this as a singleton in an activity.
I have created a module to tell how the object of CommonDataSingleton should be created.
#Module
public class SingletonModule {
#Provides
CommonDataSingleton getCommonDataSingleton() {
return new CommonDataSingleton();
}
}
And a component describing the places where the object should be injected
#Component(modules = {SingletonModule.class})
public interface SingletonComponent {
void inject(LoginActivity loginActivity);
void inject(LoginPresenter loginPresenter);
}
Along with this I have another Component for injecting completely different objects.
#Component(modules = {PresenterModule.class})
public interface DiComponent {
//to update the fields in the activities
void inject(LoginActivity loginActivity);
void inject(HomeActivity homeActivity);
}
But I get this weird error stating
DiComponent (unscoped) may not reference scoped bindings:
#Singleton test.in.singleton.CommonDataSingleton
I'll provide you some sketch, haven't tested it. Let me know whether some edits must be done here, but the concept is the following:
public class CommonDataSingleton {
private String authToken;
private boolean isAuthenticated;
}
#Module
public class SingletonModule {
#Singleton
#Provides
CommonDataSingleton getCommonDataSingleton() {
return new CommonDataSingleton();
}
}
#Singleton
#Component(modules = {SingletonModule.class})
public interface SingletonComponent {
void inject(LoginActivity loginActivity);
void inject(LoginPresenter loginPresenter);
CommonDataSingleton providesCommonDataSingleton();
}
#YourCustomScopeHere
#Component(modules = {PresenterModule.class}, dependencies = {SingletonComponent.class})
public interface DiComponent {
//to update the fields in the activities
void inject(LoginActivity loginActivity);
void inject(HomeActivity homeActivity);
}

Presenter injection with Dagger 2

I just started using Dagger 2 and I found online thousands guides each one with a different implementation and I'm a bit confused now.
So basically this is what I wrote at the moment:
AppModule.java:
#Module
public class AppModule {
Application mApplication;
public AppModule(Application application) {
mApplication = application;
}
#Provides
#Singleton
Application providesApplication() {
return mApplication;
}
}
DataModule.java:
#Module
public class DataModule {
private static final String BASE_URL = "http://beta.fridgewizard.com:9001/api/";
#Provides
#Singleton
NetworkService provideNetworkService() {
return new NetworkService(BASE_URL);
}
#Provides
#Singleton
SharedPreferences provideSharedPreferences(Application app) {
return PreferenceManager.getDefaultSharedPreferences(app);
}
}
PrefsModel.java:
#Module(includes = DataModule.class)
public class PrefsModel {
#Provides
#Singleton
QueryPreferences provideQuery(SharedPreferences prefs) {
return new QueryPreferences(prefs);
}
}
AppComponent.java (I'm exposing QueryPreferences object since I need it in a presenter, hopefully is correct in this way):
#Singleton
#Component(modules = {AppModule.class, DataModule.class, PrefsModel.class})
public interface AppComponent {
void inject(HomeFragment homeFragment);
QueryPreferences preferences();
NetworkService networkService();
}
Then I have the FwApplication.java:
public class FwApplication extends Application {
private static final String TAG = "FwApplication";
private NetworkService mNetworkService;
private AppComponent mDataComponent;
#Override
public void onCreate() {
super.onCreate();
buildComponentAndInject();
}
public static AppComponent component(Context context) {
return ((FwApplication) context.getApplicationContext()).mDataComponent;
}
public void buildComponentAndInject() {
mDataComponent = DaggerComponentInitializer.init(this);
}
public static final class DaggerComponentInitializer {
public static AppComponent init(FwApplication app) {
return DaggerAppComponent.builder()
.appModule(new AppModule(app))
.dataModule(new DataModule())
.build();
}
}
}
Finally I added another module for the presenters:
#Module
public class PresenterModule {
#Provides
Presenter<FwView> provideHomePresenter(NetworkService networkService) {
return new HomePresenterImpl(networkService);
}
#Provides
Presenter<FwView> provideSearchPresenter(NetworkService networkService) {
return new SearchPresenterImpl(networkService);
}
}
And the following component (which returns error because I cannot add a scoped dependencies here):
#Component(dependencies = AppComponent.class, modules = PresenterModule.class)
public interface PresenterComponent {
void inject(HomePresenterImpl presenter);
}
So, I have few questions that are not clear for me reading the documentation online:
How can I fix the error in the presenter component since it depends on NetworkService which is a singleton defined in the AppComponent?
I have an HomeFragment which should implement the HomePresenter with "new HomePresenter(networkService)" but now I don't know how to use the DI defined
EDIT - FIX:
HomeFragment.java:
public class HomeFragment extends Fragment {
private static final String TAG = "FW.HomeFragment";
#Inject
HomePresenterImpl mHomePresenter;
public static HomeFragment newInstance() {
return new HomeFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FwApplication.component(getActivity()).inject(this);
}
Then I modified the presenter constructor in this way:
#Inject
public HomePresenterImpl(NetworkService networkService) {
mNetworkService = networkService;
mInteractor = new InteractorImpl(mNetworkService);
}
Then NetworkService is injected automatically.
I was wondering if it is correct in this way since I have to call for every fragment I have that needs a presenter constructed in the same way as the one above the following code:
FwApplication.component(getActivity()).inject(this);
You are mixing thing up. To provide your presenter, you should switch to something like the following:
Use constructor injection if possible. It will make things much easier
public class HomePresenterImpl {
#Inject
public HomePresenterImpl(NetworkService networkService) {
// ...
}
}
To provide the interface use this constructor injection and depend on the implementation:
Presenter<FwView> provideHomePresenter(HomePresenterImpl homePresenter) {
return homePresenter;
}
This way you don't have to call any constructors yourself. And to actually inject the presenter...
public class MyFragment extends Fragment {
#Inject
Presenter<FwView> mHomePresenter;
public void onCreate(Bundle xxx) {
// simplified. Add your modules / Singleton component
PresenterComponent component = DaggerPresenterComponent.create().inject(this);
}
}
This way you will inject the things. Please read this carefully and try to understand it. This will fix your major problems, you still can not provide 2 presenters of the same type from the same module (in the same scope)
// DON'T
#Provides
Presenter<FwView> provideHomePresenter(NetworkService networkService) { /**/ }
#Provides
Presenter<FwView> provideSearchPresenter(NetworkService networkService) { /**/ }
This will not work. You can not provide 2 objects of the same kind. They are indistinguishable. Have a look at #Qualifiers like #Named if you are sure this is the way you want to go.
You do not have to provide Presenter if #Inject annotation is used in the constructor. #Inject annotation used in the constructor of the class makes that class a part of dependencies graph. So, it also can be injected when needed.
On the other hand, if you add #Inject annotation to fields, but not to constructors, you have to provide that class.

set property of base class in derived class with spring annotations

I've a base class with a property that should be set in the derived class. I've to use annotations. How's that possible?
I know how do this with xml spring configurations, but not with annotations, because I've to write them at the property?
Here's some example code:
public class Base {
// This property should be set
private String ultimateProperty;
// ....
}
public class Hi extends Base {
// ultimate property should be "Hi" in this class
// ...
}
public class Bye extends Base {
// ultimate property should be "Bye" in this class
// ...
}
How is this possible with annotations?
Some options depending on what else Base has:
class Base {
private String ultimateProperty;
Base() {
}
Base(String ultimateProperty) {
this.ultimateProperty = ultimateProperty;
}
public void setUltimateProperty(String ultimateProperty) {
this.ultimateProperty = ultimateProperty;
}
}
class Hi extends Base {
#Value("Hi")
public void setUltimateProperty(String ultimateProperty) {
super.setUltimateProperty(ultimateProperty);
}
}
class Bye extends Base {
public Bye(#Value("Bye") String ultimateProperty) {
setUltimateProperty(ultimateProperty);
}
}
class Later extends Base {
public Later(#Value("Later") String ultimateProperty) {
super(ultimateProperty);
}
}
class AndAgain extends Base {
#Value("AndAgain")
private String notQuiteUltimate;
#PostConstruct
public void doStuff() {
super.setUltimateProperty(notQuiteUltimate);
}
}
Of course, if you really just want the name of the class there, then
class SmarterBase {
private String ultimateProperty = getClass().getSimpleName();
}
Annotations for fields are linked directly to the source code in the class. You may be able to do what you are looking for via Spring EL with-in an #Value annotation, but I think the complexity overrides the value.
A pattern you may want to consider is using #Configuration annotation to programmatically setup your application context. That way you can define what is injected into the base class.

Categories