10

I have a package "Utils" where i have many classes. Some of them are just some classes with static methods and others some singleton where i pass some parameters in constructor (with @Value in order to replace the basic XML configuration by annotation).

I have a configuration in ApplicationContext in order to scan the package.

So, my question : for classes with static methods, should we transform them with @Component annotation in order to have a singleton (still with static methods) or should we let them in this state without managed them by Spring ?

thank you

Naeem Ul Wahhab
  • 2,465
  • 4
  • 32
  • 59
MychaL
  • 969
  • 4
  • 19
  • 37
  • See http://stackoverflow.com/questions/4370683/inject-util-class-with-google-guice-vs-static-methods – axtavt Dec 06 '12 at 14:52

2 Answers2

3

If it has any kind of state to maintain, or any collaborators then make a Spring component. If the functionality you need is stateless and doesn't rely on the state of any other methods it calls then make it static.

For example in my app I have a static util method that clamps integers between a min and max value, but a Spring bean that returns the current date...

@Service
public class DateServiceImpl implements DateService {
    @Override
    public Date getCurrentDate() {
        return Calendar.getInstance().getTime();
    }
}

Why? Because now I can unit test code that uses the current date.

Zutty
  • 5,357
  • 26
  • 31
  • I didn't understand your example. If i have a public static method which return a String depends on the parameters passed to the method without storing anything, so we should let the static method, and not manage the class by Spring. That's right ? in other case, create a Component or Service. – MychaL Dec 06 '12 at 15:56
  • More important: during testing you can inject a different DateServiceTestingImpl with different dates to test how your system work on different dates. Of course, in this case you will need to set it by configuration and not autowire it – borjab Jun 26 '15 at 08:11
0

With Spring it is always better to have Components then Util classes with static methods.

However if you have a lot of util classes with static methods already, refactoring could be difficult, because of, besides of replacing the util classes with Spring beans you also will have to update all methods invocations in classes depending on those utils classes. This is even harder if your code used as library in other projects. Though this is well known and is the consequence of tight coupling, which leads to fragility. Somebody will have to pay for that.

Thus I would create all new classes as Spring beans (components) but about older code I would may be left it as is, because large change could break something unintentionally. So I would replace older util classes in case I have some feature update task on them.

Here some details: https://stackoverflow.com/a/76304657/4776689

P_M
  • 2,723
  • 4
  • 29
  • 62