Spring应用程序中的实用程序类 - 我应该使用静态方法吗? [英] Utility class in Spring application - should I use static methods or not?

查看:138
本文介绍了Spring应用程序中的实用程序类 - 我应该使用静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个实用程序类DateUtil(见下文)。要使用此方法
,调用方法使用DateUtils.getDateAsString(aDate)。删除静态修饰符
并使DateUtil成为一个spring bean(参见DateUtilsBean)并将其注入调用类
或者保留原样是不是更好?

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) and 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版本

Spring Bean version

@Component
public class DateUtilsBean {

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


推荐答案

我不这么认为。 DateUtils类听起来像一个纯实用程序类,它没有任何副作用,只是处理输入参数。这种功能也可以保留在静态方法中。我不认为你很可能想要模拟约会辅助方法。

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.

这篇关于Spring应用程序中的实用程序类 - 我应该使用静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆