为何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-3845Inject 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);
  }
}
<!--spring-test.xml-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="com.springapp.mvc.pay"/>
<!--spring-mock.xml-->
<mockito:mock id="orderPaymentDAO" class="com.springapp.mvc.pay.OrderPaymentDAO"/>

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

  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,在思考问题的时,会顺着一些固有的思路一直走下去,走到一个节点发现过不去了,就纠结着如何解决这个问题,而很少去考虑思考路径是否正确,甚至思考的出发点是否就错了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,881评论 4 368
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,052评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,598评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,407评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,823评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,872评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,037评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,778评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,505评论 1 247
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,745评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,233评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,568评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,231评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,141评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,939评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,954评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,784评论 2 275

推荐阅读更多精彩内容