我们应该避免在不需要时使用 spring 托管 bean 吗?

should we avoid to use spring managed bean when it is unnecessary?

假设我有一个相对复杂的 class,需要通过分成几个较小的助手 class 来简化它。一种建议的重构解决方案是:

public class RefactoredComplexClass {
    private final Helper1 h1;
    private final Helper2 h2;
    // Helper1 and Helper2 will be injected by spring IoC
    public RefactoredComplexClass(Helper1 h1, Helper2 h2) {
        this.h1 = h1; this.h2 = h2;
    }
} 
public class Helper1 {// no state class
    public int add(int x, int y) { return x + y ; }
}

之所以提出上述建议,主要是为了简化基于 mockito 的测试。

我的问题是: 1. 没有state helper的应该使用静态方法而不是实例方法class? 2.注入那些Helper对象是个好主意吗?

我自己的想法是应该使用静态方法,因为没有状态需要为那些助手维护 class/method。并且不需要注入那些 helper classes 的实例。但我确实同意上述解决方案在一定程度上使基于 mockito 的测试更容易,因为静态方法很难模拟。

有什么建议吗?

嗨^^你想改变/指定/给不同的助手吗?

如果是:

1 : You are using the visitor pattern ( Helpers are in fact here visitors)... This is a good pattern, even if it may generate many classes. It let you change the behaviour of your RefactoredComplexClass without touching its code, even at runtime, and that is great.

Instead, using static method is simpler but to change behaviour, you need to Override your RefactoredComplexClass.

Well in general I prefer composition to extensions...

2 : That is not a bad idea at all... It let you specify the bahviour of your class from Spring file.

在其他情况下,保持简单确实是个好主意。

看看你的例子,静态方法似乎是可行的方法,也就是说,如果你确定助手 classes 绝对是无状态的,你可以很好地测试静态方法和所有classes 中的方法只是一堆实用方法。 (例如 java.lang.Math)

静态方法的一些注意事项:
1)静态绑定和更好的性能。 2) 没有创建对象。 3)方法不能被覆盖 4)难以模拟 5) 提前初始化

基于 Spring 的单例的注意事项(无状态助手最好是单例并注入您的 class)
1)你至少有一个对象——你受益于继承、多态等 2)可以延迟加载 3)易于模拟测试

你可以阅读这个 useful article