What is proper way to create objects inside method using Guice - java

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;
}
}

Related

Mocking public method inside a private method

I have a class like below:
public class ClassOne {
public function1(input, output, context) {
//some implementation
private function2(List, String, String);
}
private void function2(List, String, String){
Class2 class2 = new Class2();
String value = class2.method1(string, string);
}
}
public Class2 {
public String method2(string, string) {
//some implementation
return string;
}
}
I am writing Unit test for ClassOne using Mockito and PowerMockito and would like to mock the call to class2 and do not want to actually call method body for method2. How can I achieve this?
I tried Mockito.mock and PowerMockito.spy the class and when(class2.method2).thenReturn() and doReturn().when(class2).method2(); but everything calls the method body when I do classOne.function1. I have spied the ClassOne.
It would be really helpful if you would have also provided your non working Unit Tests. On the other hand I'm pretty sure the problem isn't there anyway :)
Your problem is not that Mockito & PowerMockito are not working.
The real problem is in the dependency of you classes. Or to be more specific the way your classes handle this dependency.
In General it is not a good idea to instantiate the dependency (Class2) in the place it is needed (ClassOne). As you can see right now it makes testing pretty hard.
It would be better to pass the dependency into the class that needs it.
This is called Dependency Injection (DI).
In your example you would pass an object of Class2 into the constructor of ClassOne. The Code would look something like that:
public class ClassOne {
private final Class2 class2;
public ClassOne(Class2 class2) {
this.class2 = class2;
}
...
private void function2(List, String, String){
String value = class2.method1(string, string);
}
}
As you can see you simply pass an instance of your dependency and use this one instead of creating it on your own.
In your Unit Test you are now able to pass a Mock of Class2 into your Class1 object which will then be used.

Passing one instance of an object to different classes without using static or singleton

I am trying to figure out a way to pass one instance of the same class to multiple classes so I am able to build an object. The problem is it cannot be static or use singleton because many users will be hitting the application at the same time and I may run into other issues. Are there any design patterns that would work best with this scenario or if there is some way to use global variables in java? I am trying implement this with an existing rest service that was not designed very well.
public class OneInstanceOf
{//I want to build this map object without static
private Map<String, String> mapIwantToBuild = new HaspMap<String, String>();
public void methodIwantToCall(String name, String value)
{mapIwantToBuild.put(name, value)
}
The common pattern for you task is dependency injection. You can use spring framework for that task.
1.Create configuration with your bean:
#Configuration
public class YourConfiguration {
#Bean
public OneInstanceOf oneInstanceOf {
return new OneInstanceOf();
}
}
2.Inject your bean whatever you want (simplest - use autowiring):
#Component
public class Client1 {
#Autowire
private OneInstanceOf oneInstanceOf;
public void someMethod() {
oneInstanceOf.methodIwantToCall();
}
}
Spring will insure single instance of oneInstanceOf will be injected in all clients.
U can create a setter with parameter of instance class variable, in every class in which you want to pass the instance. Then create a method in one of the classes that calls setter of all those classes and pass parameter instance as parameter to that method.
Like below.
class A{
B b = new B;
set(B b){
C.setB(b);
D.setB(b);
E.setB(b);
}
}

Accessing super class object

So I have this class:
public class ServiceClass {
public static Validator validator;
public ServiceClass() {
if (validator == null) validator = new Validator();
}
}
Now I have an extended class:
public class Service1 extends ServiceClass {
public Service1() {
validator.init();
}
}
Is that the right way to access the validator object? Do I have to create get ans set methods on super class? Should I use super.validator.init(); ?
Thankyou in advance.
I would use getter and setter, since they allow you to control the access way better than directly accessing the element.
Apart from that, yes, that is correct.
Also: note that you use validator as "static", that means every object of ServiceClass or any child will share the same object (they won't have each an object of that class), so be careful with your what you do with that.

Appropriate way to pass instance of class to other classes (Java)

I have a main class which has a number of instance related methods that are often needed in other classes and I often find myself passing an instance of the main class in the constructor. I often find this goes several layers deep with classes having instances of the main class that has been copied from instance to instance which I can't imagine is good for memory usage.
Is there a way to do this without having to pass the instance in the constructor or a method or at least a way to reduce the memory that is used by the instances of the main class.
To make it clear I am not looking for static methods, it is designed to be able to have more than one instance of the main class.
Example code:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public void someMethod() {
//Do something
}
}
public class Class2 {
private final Main instance;
public Class2(Main instance) {
this.instance = instance;
Class3 class3 = new Class3(instance);
}
}
public class Class3 {
private final Main instance;
public Class3(Main instance) {
this.instance = instance;
instance.someMethod();
}
}
You can use Dependency Injection Design Pattern.
Dependency-Injection-Design-Pattern
Spring, Google Guice and Java EE CDI frameworks facilitate the
process of dependency injection through use of Java Reflection API and
java annotations. All we need is to annotate the field, constructor or
setter method and configure them in configuration xml files or
classes.
You could also use dependency injection to pass on the dependent attributes or objects to required classes.
One such popular framework is Google Guice.
You could make methods like someMethod() in the Main class static, or if that's not possible, make the Main class itself a singleton.
Example of the former approach:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public static void someMethod() {
//Do something
}
}
Now you don't have to pass an instance of Main around any more, because other classes can just call Main.someMethod() directly.

Guice injector inside a thread

I have a doubt using Guice. I have a class that I call Main that is constructor injected using Guice and a method that every time that is called creates an o thread object of class AppThread. AppThread is a private class inside Main. The problem is that inside the execution of the thread I want to create an object of class ClassX. This object is constructor injected using Guice. I don't know what's the best form to inject the objects of ClassX. My first solution is inject the Injector inside Main and inside the thread use the injector to inject the objects of class ClassX.
Does exists a cleaner approach to inject the dependences inside the thread?
Thanks
Instead of having your own subclass of Thread (which is discouraged anyway) you should write your "thread code" as a regular object that implements Runnable. Your Main class should inject this class (or you can actually inject a Provider<MyRunnable> if you need to instantiate an unknown number of them). Then your Main class can create a new Thread(myRunnable) and it should all fit together nicely.
public class MyMainClass {
#Inject
MyMainClass(Provider<MyRunnable> runnableProvider) { ... }
public void spawnThread() {
new Thread(runnableProvider.get()).start();
}
}
public class MyRunnable implements Runnable {
#Inject
MyRunnable(ClassX myX) { ... }
public void run() {
... do work ...
}
}

Categories