3

In one of our legacy code base, I found the following pattern being used which seems to be a bit fragile. Consider the following Spring Bean:

 @Component
 public class PropsProvider {
     private static Properties props;

     @Inject
     PropsProvider(Configuration config) {
         PropsProvider.props = ConfigurationConverter.getProperties(config);
     }

     public static String getProperty(String key) {
         return props.getProperty(key);
     }
}

which will then be referred inside a plain Java class in a static way as shown below:

public class UrlUtil {
    private static String IMAGE_URL;

    static {
        IMAGE_URL = PropsProvider.getProperty("image_url");
    }

    private UrlUtil() {}

    public static void String getImageUrl() {
        return IMAGE_URL;
    }
}

Can there be an instance where during the server start-up time, the static block in UrlUtil gets executed before the Spring bean PropsProvider gets initalized leading to UrlUtil.getImageUrl() returning null to some caller class?

6harat
  • 542
  • 6
  • 18
  • `UrlUtil` would fail to initialize if `PropsProvider` wasn't initialized first, because `getProperty()` would throw a NPE. If you ask me, the real smell is that you're using a constructor to initialize a static field. – shmosel Sep 13 '18 at 00:52
  • @shmosel thanks for pointing it out that there would be an NPE and UrlUtil would fail to initialize. Is this dependency resolved by Java's class loader which sees that the static block is dependent on some other class or is it taken care of in the Spring Lifecycle where Spring Beans are given priority over the plain Java classes? – 6harat Sep 13 '18 at 00:58
  • Neither. It's just a matter of chronology. Classes are normally initialized when they're first used. As long as `UrlUtil` isn't referenced before `PropsProvider` is initialized, you should be fine. Depending on your environment, the order might be well-defined, or it might just work by chance. – shmosel Sep 13 '18 at 01:07
  • I think that confirms the OP's concerns: yes it seems quite brittle. At least, as a non-expert on Spring and how it initializes itself, it scares the bejesus out of me. – markspace Sep 13 '18 at 01:09

0 Answers0