0

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.

shadows
  • 121
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/19619118/what-is-the-right-way-to-use-an-injected-bean-in-a-static-method can you check this question? – Sharofiddin Apr 28 '22 at 09:49
  • @Sharofiddin I tried PostConduct, and still it is not working. However, as I mentioned, these solutions are working in a new demo project. Thanks for your suggestion. – shadows Apr 28 '22 at 10:59

1 Answers1

2

The example you showed is not proper solution. You shouldn't declare Utility class that suppose to have just static methods as a bean (Component). That creates an instance of Utility class and all injected properties are properties of an instance, that you should not access from static method. Static method should only perform stateless logic i.e. it could only rely on parameters passed to it through the method only and should never access internal properties that were not passed into the method. Otherwise it becomes "Evil static method" and you will get more troubles than its worth from it. If you need to use internal logic such as injected bean you have to use regular bean with non-static method, i.e. your logic is not a good candidate for Utils static method

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36