Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring dependency injection vs static classes for utilities? [duplicate]

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?

like image 279
Andreas Hartmann Avatar asked Oct 15 '25 03:10

Andreas Hartmann


1 Answers

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.

like image 167
Milgo Avatar answered Oct 18 '25 05:10

Milgo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!