gpt4 book ai didi

java - Spring 与否 Spring : should we create a @Component on a class with static methods?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:56 25 4
gpt4 key购买 nike

我有一个包“Utils”,其中有很多类。其中一些只是一些带有静态方法的类,其他一些是我在构造函数中传递一些参数的单例(使用@Value 以便通过注释替换基本的 XML 配置)。

为了扫描包,我在 ApplicationContext 中进行了配置。

所以,我的问题是:对于具有静态方法的类,我们应该使用 @Component 注释转换它们以便拥有单例(仍然使用静态方法)还是应该让它们处于这种状态而不由 Spring 管理它们?

谢谢

最佳答案

如果它有任何类型的状态需要维护,或者有任何合作者,那么就制作一个 Spring 组件。如果您需要的功能是无状态的,并且不依赖于它调用的任何其他方法的状态,则将其设为静态。

例如,在我的应用程序中,我有一个静态 util 方法,它将整数限制在最小值和最大值之间,但是一个返回当前日期的 Spring bean...

@Service
public class DateServiceImpl implements DateService {
@Override
public Date getCurrentDate() {
return Calendar.getInstance().getTime();
}
}

为什么?因为现在我可以对使用当前日期的代码进行单元测试。

关于java - Spring 与否 Spring : should we create a @Component on a class with static methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com