开发者

Utility class in Spring application - should I use static methods or not?

开发者 https://www.devze.com 2023-04-01 16:06 出处:网络
Let\'s say I have a utility class DateUtil (see below). To use this method a caller method uses DateUtils.getDateAsString(aDate). Would it be better to remove

Let's say I have a utility class DateUtil (see below). To use this method a caller method uses DateUtils.getDateAsString(aDate). Would it be better to remove the static modifier and make DateUtil a spring bean (see DateUtilsBean) a开发者_开发百科nd inject it into calling classes or just leave it as is?

One disadvantage I can see with using static is issues around mocking, see How to mock with static methods?

public class DateUtils {

    public static String getDateAsString(Date date) {       
        String retValue =  "" // do something here using date parameter
        return retValue;
    }
}

Spring Bean version

@Component
public class DateUtilsBean {

    public String getDateAsString(Date date) {      
        String retValue =  "" // do something here using date parameter
        return retValue;
    }
}


I don't think so. A DateUtils class sounds like a pure utility class that doesn't have any side effects but just processes input parameters. That kind of functionality may as well remain in a static method. I don't think it's very likely that you'll want to mock date helper methods.


I agree with Sean Patrick Floyd.

This is my criterion: if the methods of the class do things only over the parameters they receive, with no external dependencies (database, file system, user config, other objects/beans, etc.), then I would do it with static methods, usually in a final class with a private constructor.

Otherwise, I would implement it using a Spring bean.

So, in the case that you raise, according to this criterion, I would write a class with static methods.

Regards.


It would be better to declare it as a Spring bean because the life cycle of it is then managed by Spring, and you can eventually inject dependencies, pool the object, as well as test it in a proper way, not to talk that you could use it as a regular object and pass it as parameter, redefine the method in subclasses... etc.

In short, yes it would be a better design in most cases. Nevertheless, in a case as simple as the exposed, it doesn't do a great difference.


A good answer in this comment Should I use static at all in spring singleton beans

static variable has one instance in one JVM. Singleton exists per spring context. If your application has only one context, they do the same job.

But do not mix them together. In some old projects, I see some not-pure utility class using some spring bean via ApplicationContext. It is very hard to write test case for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消