3

In a Spring application, if I have Utility method I want to use throughout my project, should I use a static method in a Utility class or an Autowired @Component?

So for example I could have a CalculatorUtility.class with

public static int add(int a, int b){...}

Or I could have a CalculatorComponent.class like this and Autowire it:

@Component
public class CalculatorComponent {
public int add(int a, int b){...}}

I'm assuming that the calculator doesn't require any dependencies. I was thinking autowiring it may be more flexible in case I need to add a dependency in the future, while static is just simpler. Are there guidelines for this?

Andreas Hartmann
  • 1,825
  • 4
  • 23
  • 36
  • In my opinion, and given that you are already using Spring, the question is why you would NOT want to autowire ? I've found you tend to get bitten a lot more with static methods compared with using instances. – racraman Apr 23 '19 at 06:41

1 Answers1

2

You are right, a static method in a utility class cannot use any Spring dependency. So if there is any chance that you need an other class for your method or that you might add additional funcionality, you should use a Spring @Component.

You can use static classes if your method is and will stay very simple and has no state behaviour. E.g. using System.out.println will always print something to the system's current PrintStream without any state or additional behaviour.

Milgo
  • 2,617
  • 4
  • 22
  • 37