Toothpick bind modules that depends on each other - java

I am trying out the toothpick DI library and I seem to miss something crucial.
I created the following test project on github where I tried to make a smallest possible use case for my understanding issue.
There you will find the ApplicationModule where I try to inject everything I need in my "root" module. As you can see there, I have twice scope.installModules(module) because my PlainPojo depends on the Application instance. If I do not do the first installModule call, I have no application instance in the scope. I could, as mentioned in the comment, pass the application instance as a parameter but I thought that I can remove them when I use DI?
The second class that causes troubles is the SimpleTest class. If I do not call the inject() method in the constructor, the PlainPojo member will not be injected. I also tried to use a third time the installModules() in the ApplicationModule after binding the PlainPojo but that does not help.
Am I so wrong to assume that an #Inject on a member is enough to automatically inject it when it is available in the scope and that the order of binding is enough to make previous bindings available without installing in between (like done in ApplicationModule)?
If I can provide anything more to make my issue(s) understandable please leave a comment.
Thanks in advance!

Toothpick can only inject dependencies automatically when it creates the instance of the depended object itself (e.g it is annotated with #Singleton or there is a direct binding for the class).
Otherwise you have to manually call Toothpick.inject, just like you do in SimpleTest. There is no way for TP to know when you call the constructor of PlainPojo.
You could just use
module.bind(PlainPojo.class);
module.bind(SimpleTest.class);
and maybe scope them as singletons if needed.

Related

If you need dependency injection, put cucumber-picocontainer on the classpath

Keep getting this error and I am now at my wits end, can anyone explain what I may be doing wrong please - apparently might have to do with cucumber versions, how does one make the versions match:
io.cucumber.core.exception.CucumberException: class stepDefinitions.SearchStepsUser doesn't have an empty constructor. If you need dependency injection, put cucumber-picocontainer on the classpath
stepDefinition file
code
io.cucumber.core.exception.CucumberException: class stepDefinitions.SearchStepsUser doesn't have an empty constructor
That means that your SearchStepUser should not have this constructor:
public SearchStepsUser(StepData stepData) {
this.stepData = stepData;
}
You need to remove this constructor. If you need to store StepData, create some utility class to store it and provide it during your test step execution. In fact, StepData could (should) be this utility class with static methods that could be easily invoked during execution of your tests.
Alternatively, the error message is recommending the use of picocontainer if Dependency Injection (what you are doing by passing StepData through the constructor) is needed. If you require DI, just search the web for a picocontainer tutorial.

Is it possible to implement/override an abstract method with reflection?

I have a question about Reflection, but the motivation is from using Spring Framework.
Consider this project, which is a sort of Minimum Working Example version of a deployed project.
In the ProjectionResourceProcessorConfig class, I have an entityProjectionResourceProcessor method for every projection, and every entity in the database have a few projections. That's about 60 methods.
I don't want to keep this up because of the obvious maintenance disadvantage. I want to use Reflection in order to automatically register one bean for every projection class.
The postProcessBeanDefinitionRegistry method in the ProjectionResourceProcessorConfig class shows that I can get the list of classes I want to use to register one bean for each and shows how to register a bean programatically.
However, because I need to use the ProjectionResourceProcessor class, I need to override the getEntityClass method. I haven't been able to find a way to do that programatically. That's why I've declared the inner class. It shows the programatic bean registration working, but it falls in the same issue as requiring a piece of code for every bean.
Apart from reflection, I tried to use the setMethodOverrides method of the RootBeanDefinition class to override that method, but I couldn't manage to understand how to use that method. Google couldn't find any documentation or usage example (except for a vaguely related Chinese post with copies on several different websites).
I also tried to use the MethodReplacer class but I haven't found how to use it with annotation driven configuration.
I also tried to replace the getEntityClass method by a variable and replace the variable's value by reflection, but apparently when the variable is read the value that was set in the super class is the one that is retrieved.
To test the project, run the tests at DemoApplicationTests. It will print the projection of some entities. If they have links, it's working.
Is it possible to do what I want? If it is, how?
Thanks in advance.

What is the difference between autowiring and object creation?

What is the difference, if I autowire a class and provide value and instantiate an object of class and provide some value?
For example-
#Autowired
private UserService userService;
userService.findUser(userName, password);
And
User user = new user();
userService.findUser(user.getuserName(),user.getpassword());
What is the difference in Autowiring and sending the data and instantiating the object and sending the data to some service class?
I'm trying to clarify the concepts in spring.
When you use #Autowired you are leaving it up to the Spring framework to find and instantiate the userService. This is usually controlled through some configuration file or some other configuration, which allows you to change the behaviour of your application without changing the code itself.
On the other hand, when you instantiate the object yourself, you are specifying which object you are after and what type of class you want. This could leave you with less ambiguous code since you know what type of object is being initialized, but to make a change in your application's behaviour you would need to change your code.
In essence, the first option is less coupled than the second option, which is usually the recommended way of building things.
Your example doesn't make a lot of sense; this User class, which looks like some plain data object, isn't adding anything to the second snippet.
The idea of "autowiring" is that some class, like maybe a Web controller, will need a UserService in order to get its work done. When Spring autowires the UserService, it goes into the context and finds a matching object and provides it to the class that needs it. This is technically separate from creating the object.
That said, the best practice is to use constructor injection--simply declare the other objects you need as constructor parameters and annotate the constructor with #Autowired (or #Inject). Spring will know to look up all the dependencies you need and call the constructor with them. This means that it's also very simple to provide mocks of those objects for testing or development.
Well, the main difference is that in case u use #Autowired the object is also created, however, it's created by container and container decide when to do that.
I want to give you a simple example:
You have four classes 1,2,3 and 4. Three of them (1,2,3) uses the 4th. So, if you use new(), it`s hard to decide where to create object(in class 1, or 2, or 3, or even in each of them) of 4th class. Moreover, later you can delete class with object initialization and other 2 classes won't work (in case you created one object). Autowired annotation injects the object but you don't initialize object in class, so no problems appear
This is like the simplest answer.
the above answers are good i would like to tell a major difference between them .the purpose of autowiring is to avoid the dependencies between the class
if you are creating objects with new making a change to one class will effect all the classes.

How to let Guice bind an annotated injection to a single instance

I have an UI component that will be used in several UI module in an application.
I would like to annotate the UI component that to be injected into several other classes in one UI module to be a singleton, but not a singleton across the whole application. So that for each UI module use the UI component, one and only one of the UI component instance is used.
I couldn't find a straight solution for this from the Guice document. So i think maybe I can use annotation to distinguish those instance?
Say in Module A, I annotate all the injection of the UI component with Named("ModuleA"); and in Module B, with Named("ModulaB"). and in the configuration, i tried to use something like:
this.bind(UIComponentA.class)
.annotatedWith(Names.named("ModulaA"))
.to(UIComponentAImpl.class).in(Singleton.class);
this.bind(UIComponentA.class)
.annotatedWith(Names.named("ModulaB"))
.to(UIComponentAImpl.class).in(Singleton.class);
Because UICompoenetAImpl also need to be injected, so I couldn't simply create the instance there. Totally not sure if this works.
And I'm wondering what's the standard way to accomplish this?
One other option might be to use a child injector for each module.
This would allow you to bind a difference instance of UIComponentA in each module. Bind them in the child injector rather than the parent. You would then need to make sure that all of your module's dependencies are built from the right child injector, probably by making sure the root of each module is loaded from the right place.
Because UICompoenetAImpl also need to be injected, so I couldn't simply create the instance there.
I think you can just create UIComponentAImpl there and bind toInstance. When you do so - other beans will be injected in UIComponentAImpl. Please see my example here.

Is there ever a case for 'new' when using dependency injection?

Does dependency injection mean that you don't ever need the 'new' keyword? Or is it reasonable to directly create simple leaf classes such as collections?
In the example below I inject the comparator, query and dao, but the SortedSet is directly instantiated:
public Iterable<Employee> getRecentHires()
{
SortedSet<Employee> entries = new TreeSet<Employee>(comparator);
entries.addAll(employeeDao.findAll(query));
return entries;
}
Just because Dependency Injection is a useful pattern doesn't mean that we use it for everything. Even when using DI, there will often be a need for new. Don't delete new just yet.
One way I typically decide whether or not to use dependency injection is whether or not I need to mock or stub out the collaborating class when writing a unit test for the class under test. For instance, in your example you (correctly) are injecting the DAO because if you write a unit test for your class, you probably don't want any data to actually be written to the database. Or perhaps a collaborating class writes files to the filesystem or is dependent on an external resource. Or the behavior is unpredictable or difficult to account for in a unit test. In those cases it's best to inject those dependencies.
For collaborating classes like TreeSet, I normally would not inject those because there is usually no need to mock out simple classes like these.
One final note: when a field cannot be injected for whatever reason, but I still would like to mock it out in a test, I have found the Junit-addons PrivateAccessor class helpful to be able to switch the class's private field to a mock object created by EasyMock (or jMock or whatever other mocking framework you prefer).
There is nothing wrong with using new like how it's shown in your code snippet.
Consider the case of wanting to append String snippets. Why would you want to ask the injector for a StringBuilder ?
In another situation that I've faced, I needed to have a thread running in accordance to the lifecycle of my container. In that case, I had to do a new Thread() because my Injector was created after the callback method for container startup was called. And once the injector was ready, I hand injected some managed classes into my Thread subclass.
Yes, of course.
Dependency injection is meant for situations where there could be several possible instantiation targets of which the client may not be aware (or capable of making a choice) of compile time.
However, there are enough situations where you do know exactly what you want to instantiate, so there is no need for DI.
This is just like invoking functions in object-oriented langauges: just because you can use dynamic binding, doesn't mean that you can't use good old static dispatching (e.g., when you split your method into several private operations).
My thinking is that DI is awesome and great to wire layers and also pieces of your code that needs sto be flexible to potential change. Sure we can say everything can potentially need changing, but we all know in practice some stuff just wont be touched.
So when DI is overkill I use 'new' and just let it roll.
Ex: for me wiring a Model to the View to the Controller layer.. it's always done via DI. Any Algorithms my apps uses, DI and also any pluggable reflective code, DI. Database layer.. DI but pretty much any other object being used in my system is handled with a common 'new'.
hope this helps.
It is true that in today, framework-driven environment you instantiate objects less and less. For example, Servlets are instantiated by servlet container, beans in Spring instantiated with Spring etc.
Still, when using persistence layer, you will instantiate your persisted objects before they have been persisted. When using Hibernate, for example you will call new on your persisted object before calling save on your HibernateTemplate.

Categories

Resources