简体   繁体   中英

Dependency injection and static methods

I was wondering how I can make a static method work with dependency injection.
For example:

public class Util {
    Main main;

    public Util(Main main) { this.main = main }

    public static void showMessage() {
        System.out.println("message = " + main.messageMethod());
    }
} 

This is kinda what I want to do, but if I do it this way when I call the method from other class like Util.showMessage(); it tells me that main is null.
I am looking on how to make this work correctly as it would be a little annoying to DI on every static method on that class.

You need to pass Main to the static method:

public static void showMessage(final Main main) {
    System.out.println("message = " + main.messageMethod());
}

Best practices to write utility classes:

  1. Utility classes/methods has to be stateless. Utility classes should not have members. Utility methods should accept all required variables as parameters. Utility classes can be called from multiple threads in the concurrent environment. Mutable member variables make classes not thread safe and produce nasty bugs in the concurrent environment
  2. Utility methods should not be instantiated and should not be injected.They should have private constructor.
  3. Utility classes should be final (not extendable).

After applying these rules to your utility class it will look like:

public final class Util {

    private Util();

    public static void showMessage(final Main main) {
        System.out.println("message = " + main.messageMethod());
    }
}

This class is final (can't be extended), has private constructor (can't be instantiated or injected), stateless (no members, thread-safe if method showMessage it's not changing the state of the main variable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM