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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With