Currently I need to write SecondClassand decided to write using such a solution, because otherwise it would be impossible to verify.
@Component
public class FirstClass {
public void doStuff() {
System.out.println("First Class stuff!");
}
}
@Component
public class SecondClass {
private final Random random;
private final FirstClass firstClass;
@Autowired
public SecondClass(FirstClass firstClass) {
this(new Random(), firstClass);
}
public SecondClass(Random random, FirstClass firstClass) {
this.random = random;
this.firstClass = firstClass;
}
public void doOtherStuff() {
firstClass.doStuff();
System.out.println("Second Class stuff " + random.nextInt(10));
}
}
My colleagues did not like my way of solving this issue and preferred the implementation SecondClassas follows:
@Component
public class SecondClass {
private Random random;
private final FirstClass firstClass;
@Autowired
public SecondClass(FirstClass firstClass) {
this.random = new Random();
this.firstClass = firstClass;
}
public void doOtherStuff() {
firstClass.doStuff();
System.out.println("Second Class stuff " + random.nextInt(10));
}
public void setRandom(Random random) {
this.random = random;
}
}
I do not agree with this decision, because I believe that it Randomis a necessary part of this class, it will not be changed at runtime, and this setter is needed only for testing purposes, and therefore I prefer a solution with two constructors.
We also created such a constructor:
@Autowired(required = false)
public SecondClass(FirstClasss firstClass, Random random) {
this.random = (random == null ? new Random() : random)
...
}
But in fact, more components have been added to the constructor, so it would be preferable if all of them were necessary.
, - ? ?