Home > Net >  Spring - Difference between using static method and @Component
Spring - Difference between using static method and @Component

Time:10-28

I'm working on Java Spring

I wanna make simple Util methods like 'get current time as string, split string on special condition, etc..)

I think there is two ways to develop;

1. using static method

/* using static method */
public class TestUtil {
  public static String printTest() {
    System.out.println("test!");
  }
}

// Call Method
public class Caller {
  public void callTest() {
    TestUtil.printTest();
  }
}

2. set as component

/* using as @component */
@Component
public class TestUtil {
  public String printTest() {
    System.out.println("test!");
  }
}


// Call Method
public class Caller {

  @Autowired
  TestUtil testutil;

  public void callTest() {
    testutil.printTest();
  }
}

Which of the two looks better? And What is the main difference?

Can you answer, you have great mercy on this miserable junior developer. Thank for your answer

CodePudding user response:

First of all, you shouldn't use a static method to get the time. You can inject a Clock implementation into spring components so that tests can substitute their own predictable clock. That way code that gets the time can assert the expected value of the time.

Spring has control over how it creates component objects but it has no control over classloading, spring can't control which class loads first and make sure static fields have valid values at a given time. It's always better not to use static methods in spring for anything but code that has no dependencies or side effects whatsoever.

  • Related