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:
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.