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?

1 Answers

0
Milgo On

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.