为何Spring无法注入静态域?

There is no dumb question.

文章下半段更精彩

使用Spring DI过程中试图注入静态域或静态方法时,Spring会报如下Warning,导致未注入:


//测试代码
@Value("${member}")
private static String member;

//输出信息
一月 12, 2017 3:35:15 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor buildAutowiringMetadata
警告: Autowired annotation is not supported on static fields: private static java.lang.String com.springapp.mvc.statictest.StaticTestBean.member

解决方案

解决方案如下:

使用构造方法、代理的setter亦或init-method来将静态域值注入

//1. via constructor
public class StaticTestBean {

  private static String member;
  
  public StaticTestBean(String member) {
    StaticTestBean.member = member;
  }
}

//2. via setter
public class StaticTestBean {

  private static String member;
  
  public void setMember(String member) {
    StaticTestBean.member = member;
  }
}
  
//3. via init-method
public class StaticTestBean {

  private static String member;
  
  @Value("${member}")
  private String _member;

  @PostConstruct
  public void init() {
    StaticTestBean.member = _member;
  }
}

那么问题来了:

Spring为什么不允许注入静态域?

首先可以确定的是,静态域注入肯定是可以,可以看下面这段比较Evil的实现:

//quote from http://stackoverflow.com/a/3301720/1395116
import java.lang.reflect.*;

//Evil
public class EverythingIsTrue {
   static void setFinalStatic(Field field, Object newValue) throws Exception {
      field.setAccessible(true);

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }
   public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);

      System.out.format("Everything is %s", false); // "Everything is true"
   }
}

那么是Spring IoC的无法实现么?

//check org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
if (annotation != null) {
    if (Modifier.isStatic(field.getModifiers())) {
        if (logger.isWarnEnabled()) {
            logger.warn("Autowired annotation is not supported on static fields: " + field);
        }
        continue;
    }
    boolean required = determineRequiredStatus(annotation);
    currElements.add(new AutowiredFieldElement(field, required));
}

//injection org.springframework.beans.factory.annotation.InjectionMetadata
protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable {
    if (this.isField) {
        Field field = (Field) this.member;
        ReflectionUtils.makeAccessible(field);
        field.set(target, getResourceToInject(target, requestingBeanName));
    }
    else {
        if (checkPropertySkipping(pvs)) {
            return;
        }
        try {
            Method method = (Method) this.member;
            ReflectionUtils.makeAccessible(method);
            method.invoke(target, getResourceToInject(target, requestingBeanName));
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

注入实现时发现如果为静态域及方法时直接操作下一个属性或方法,观察对于非静态属性或方法的注入操作时,是可以完成对静态域的注入的,所以说这个warning并不是实现不支持,即对静态域注入的检查不是一个bug,而是一个feature,所以开篇举例的解决方案其实只是一些workaround的方案,本质上企图通过反射修改静态域就是有问题,此问题的讨论可以参考官方开发者的一段回复:

The conceptual problem here is that annotation-driven injection happens for each bean instance. So we shouldn't inject static fields or static methods there because that would happen for every instance of that class. The injection lifecycle is tied to the instance lifecycle, not to the class lifecycle. Bridging between an instance's state and static accessor - if really desired - is up to the concrete bean implementation but arguably shouldn't be done by the framework itself.

更多可参考:SPR-3845及Inject bean into static method#comment

在寻找不能注入静态域的过程中,想起了以前编写单元测试时类似的场景:

单元测试为什么要引入Spring?

单元测试场景很简单,要测试OrderPaymentService的save方法,其中关联了OrderPaymentDAO,为了免去OrderPaymentDAO对测试的影响,对OrderPaymentDAO的特定行为(insert)进行mock(模拟),其中使用了mockitospringokito来完成相应bean的mock以及注入,完美解决了已注入依赖行为无法被mock的问题,最终实现如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = SpringockitoContextLoader.class,
    locations = {"classpath:spring-test.xml", "classpath:spring-mock.xml"})
public class OrderPaymentServiceTest {

  @Resource
  private OrderPaymentService orderPaymentService;

  @Resource
  private OrderPaymentDAO orderPaymentDAO;//this bean is mocked

  @Before
  public void init(){
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void saveWithNormalDataTest() throws Exception {
    //build data
    OrderPaymentDO orderPaymentDO = new OrderPaymentDO();
    
    //define mock behaviour
    when(orderPaymentDAO.insert(any(OrderPayment.class))).thenReturn(2);

    //invoke
    boolean result = orderPaymentService.save(orderPaymentDO);
    
    //assert
    Assert.assertFalse(result);
  }
}





当时的思考路径应该是这样的:

  1. 因为使用了spring,变查阅spring下ut该如何编写,参考@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration()启动spring并执行单测
  2. 启动spring后注入对象的行为无法mock,便检索mock spring注入的依赖对象的行为,发现可以使用springokito

当启动测试,Spring启动了,实例化了OrderPaymentService,springokito也将orderPaymentDAO mock化并注入到orderPaymentService中并完成了后续测试,得到了一个绿色的成功结果条,以为得到了完美的方案。
最后得到的单元测试代码就变得臃肿低效,虽然最后问题解决了,整个思考过程似乎并没有什么问题。
后来参考此方式又写了一些测试用例,后来越发感觉哪里不对。忽然有一天终于开始质疑:

单元测试为什么一定要引入Spring?

然后将单元测试调整为:

public class OrderPaymentServiceTest {

  private OrderPaymentService orderPaymentService;

  private OrderPaymentDAO orderPaymentDAO;//this bean is mocked

  @Before
  public void init(){
    orderPaymentDAO = mock(OrderPaymentDAO.class);
  }

  @Test
  public void saveWithNormalDataTest() throws Exception {
    //build data
    OrderPaymentDO orderPaymentDO = new OrderPaymentDO();
    
    //define mock behaviour
    when(orderPaymentDAO.insert(any(OrderPayment.class))).thenReturn(2);

    //inject mocked orderPaymentDAO into orderPaymentService
    orderPaymentService.setOrderPaymentDAO(orderPaymentDAO);
    //invoke
    boolean result = orderPaymentService.save(orderPaymentDO);
    
    //assert
    Assert.assertFalse(result);
  }

}

没有多余配置项,UT执行时也无需等待Spring的IoC、Bean被mock过程,单元测试只剩下测试所需要的东西。

思考方式调整为:如何mock一个类的成员?最终的解决方案就显而易见了。

想起耗子叔叔的一篇旧文http://coolshell.cn/articles/10804.html,在思考问题的时,会顺着一些固有的思路一直走下去,走到一个节点发现过不去了,就纠结着如何解决这个问题,而很少去考虑思考路径是否正确,甚至思考的出发点是否就错了。

你可能感兴趣的:(为何Spring无法注入静态域?)