MychaL
MychaL

Reputation: 999

Spring or not Spring : should we create a @Component on a class with static methods?

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

Upvotes: 11

Views: 11870

Answers (2)

P_M
P_M

Reputation: 2952

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

Upvotes: 0

Zutty
Zutty

Reputation: 5377

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.

Upvotes: 3

Related Questions