0

I was trying to access the non static method from class A to a static method in class B

@Component
public class B{
private static A aA1;
@Autowired
private A tA;

@PostConstruct
public void init(){
//<<<Make the enclosed method Static or remove this set>>>
B.aA1=tA;
}

public static void random method(){
aA1.doStuff();
}
}

Is it okay to make the init method static, as the sonar suggest Or is there another way i could solve this?

HinataDev
  • 11
  • 6
  • Every construction of a `B` will set the one and only global `aA1` (with the auto-wired `tA`) which first is `null`. _Throw away this design._ Make a singleton, whatever. – Joop Eggen Aug 29 '22 at 13:57
  • @JoopEggen how can I come up with a singleton design, any reference that i could go through – HinataDev Aug 29 '22 at 14:10
  • I assume this is spring. Logging to see what happens may in be enlightening (because of spring's magic). There are many blogs and such around spring. There should rarely be a need for a `static` with spring dependency injection. But I humbly admit that I cannot give any reference. – Joop Eggen Aug 29 '22 at 14:18
  • @JoopEggen can I make the init() a static, just to clear the sonar issue. ? – HinataDev Aug 30 '22 at 06:29

0 Answers0