I have a Utility class and I need to inject a bean in Utility class and use it in a static method of the Utility class. I found a couple of solutions, but they are not working in our project. However, when I try the suggested solutions in a new demo project, suggested solutions are working.
This is the demo implementation:
Controller class:
@RestController
@RequestMapping("demo")
public class HelloController {
@GetMapping("convert")
public LocalDate hello(String value) {
return Utility.convert(value);
}
}
Utility class:
@Component
public class Utility {
private static DateConverter staticDateConverter;
@Autowired
public Utility(DateConverter dateConverter) {
Utility.staticDateConverter = dateConverter;
}
public static LocalDate convert(String value) {
return staticDateConverter.convert(value);
}
}
Bean required in Utility class:
@Component
public class DateConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String value) {
return LocalDate.parse(value);
}
}
This demo implementation is exactly implemented in out project, but it is not working interestingly. So the staticDateConverter is being null, if you consider this example, in our project.
My question is, what could be the reason why static bean injection is not working in our project?
UPDATE
If I autowire the Utility class on somewhere, staticDateConverter inits. Otherwise, staticDateConverter not being initialized, so gives null pointer exception.