0

I would like to create a helper class, but it just failed.. The error : java.lang.NullPointerException: null

When i do this without making a static class (with autowired) it works without problem. But it's a helper class, i think the static class is the better thing.

Thanks for help

Helper.java

public final class UrlHelper {
    
    @Autowired
    private static Environment bean;
    
    public static String method(String projet) {    
        return "titi"+ bean.getProperty("property.name");
    }
}

And in my service, i use it like this :

String list = getRequest.getHTTPRequest(UrlHelper.method(projet));
Kévin
  • 497
  • 10
  • 37
  • 4
    Does this answer your question? [Accessing spring beans in static method](https://stackoverflow.com/questions/12537851/accessing-spring-beans-in-static-method) – lainatnavi Feb 10 '21 at 22:23

1 Answers1

0

In Spring, the @Autowired annotation allows you to resolve and inject beans into other beans. In your case, the UrlHelper class is not a bean and therefore, your Environment is not injected (stays null), hence the error. You have two options:

  1. Make the UrlHelper a bean using @Component, @Service, etc. This will make your class non-static.
  2. Keep the UrlHelper static, and pass the Environment as parameter. This, I believe, is the more correct approach. The Environment can be injected in the class calling the static method.
  • 2 . If i inject Environment as parameter it's not better than using environment in my service.. :( – Kévin Feb 11 '21 at 07:18
  • It is. It makes sense from a design point of view that your helper class "helps" you do something, when provided with an Environment instance. This allows the class to work on any Environment you provide it, making it more versatile (as a helper class should be). – Sebastian Grigor Feb 11 '21 at 07:26
  • I want that the Environment stays in the helper class, not to inject it from a service ( because the helper will help me to build hundred of url) – Kévin Feb 11 '21 at 07:28
  • Then you have no option, but use 1. Make your helper class a bean and remove the "static" keyword from its method. You can only inject your Environment in a bean. – Sebastian Grigor Feb 11 '21 at 07:32
  • Just Make the Helper class using @Component, but the class still static. I can use the helper by UrlHelper.Foo() . – Cheung Apr 29 '22 at 07:03