Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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

like image 332
MychaL Avatar asked Nov 03 '22 09:11

MychaL


1 Answers

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.

like image 184
Zutty Avatar answered Nov 08 '22 10:11

Zutty