为什么Spring迫使我使用静态变量?

时间:2014-05-15 09:58:44

标签: java spring annotations testng static-members

我仍然是 Spring 的初学者。我有一个测试类如下TestNG ...

@Service("springTest")
public class SpringTest {
  private MyService myService;

  @Autowired
  public void setMyService(MyService myService) {
    this.myService = myService;
    // below was ok , nothing error
    System.out.println(myService.getClass());
  }

  //org.testng.annotations.Test
  @Test
  public void doSomethingTest() {
    load();
    // That may cause NullPointerException
    myService.doSomething();
  }

  private void load(){
  // here codes for load spring configuration files
  }
}

所以,我不知道为什么myService.doSomething();产生 NullPointerException ?有人可以给我建议我需要做什么吗?什么问题可能导致此错误?我错了什么?现在我正在使用......

@Service("springTest")
public class SpringTest {
  private static MyService myService;

  @Autowired
  public void setMyService(MyService myService) {
    SpringTest.myService = myService;
    System.out.println(myService.getClass());
  }
  //org.testng.annotations.Test
  @Test
  public void doSomethingTest() {
    load();
    // fine , without error
    myService.doSomething();
  }

  private void load(){
  // here codes for load spring configuration files
  }
}
  

PS :我认为我不需要显示我的弹簧配置文件,因为它非常简单,我相信不会导致任何错误。所以,我留下来描述。但如果你想看,我可以告诉你。然后请假设我的spring configurartion文件已正确加载,并且在我的测试类运行之前已加载。    感谢您阅读我的问题。顺便说一句,我也不能使用字段   注射,我只能使用setter方法注射。

1 个答案:

答案 0 :(得分:3)

只需删除静态初始化程序即可。保持二传手注射(我更喜欢)。

使用你的第一个例子,第二个代码是错误的 - 不要使用它。

确保测试是由spring运行的(因此bean会在春天正确初始化)。

在spring初始化bean之前运行test方法会导致空指针。

你需要这样的东西

@RunWith (SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = "classpath:/config/applicationContext-test.xml")
public class SpringTest {...}