title: What is the difference between @BeforeClass and Spring @TestExecutionListener beforeTestClass()
body: <p>What is the difference between using JUnit @BeforeClass and the Spring @TestExecutionListener beforeTestClass(TestContext testContext) "hook"?  If there is a difference, which one to use under which circumstances?  </p>
  
  <p>Maven Dependencies:<br/>
  spring-core:3.0.6.RELEASE <br/>
  spring-context:3.0.6.RELEASE  <br/>
  spring-test:3.0.6.RELEASE  <br/>
  spring-data-commons-core:1.2.0.M1  <br/>
  spring-data-mongodb:1.0.0.M4  <br/>
  mongo-java-driver:2.7.3  <br/>
  junit:4.9 <br/>
  cglib:2.2 <br/></p>
  
  <h2>Using JUnit @BeforeClass annotation:</h2>
  
  <pre><code>import org.junit.BeforeClass;
  import org.junit.Test;
  import org.junit.Assert;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.test.context.ContextConfiguration;
  import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
  
  @ContextConfiguration(locations = { "classpath:test-config.xml" })
  public class TestNothing extends AbstractJUnit4SpringContextTests {
  
      @Autowired
      PersonRepository repo;
  
      @BeforeClass
      public static void runBefore() {
          System.out.println("@BeforeClass: set up.");
      }
  
      @Test
      public void testInit() {
          Assert.assertTrue(repo.findAll().size() == 0 );
      }
  }
  
  =&gt; @BeforeClass: set up.
  =&gt; Process finished with exit code 0
  </code></pre>
  
  <h2>Using the Spring hook:</h2>
  
  <p>(1) Override beforeTestClass(TextContext testContext):</p>
  
  <pre><code>import org.springframework.test.context.TestContext;
  import org.springframework.test.context.support.AbstractTestExecutionListener;
  
  public class BeforeClassHook extends AbstractTestExecutionListener {
  
      public BeforeClassHook() { }
  
      @Override
      public void beforeTestClass(TestContext testContext) {
          System.out.println("BeforeClassHook.beforeTestClass(): set up.");
      }
  }
  </code></pre>
  
  <p>(2) Use @TestExecutionListeners annotation:</p>
  
  <pre><code>import org.springframework.test.context.TestExecutionListeners;  
  // other imports are the same    
  
  @ContextConfiguration(locations = { "classpath:test-config.xml" })
  @TestExecutionListeners(BeforeClassHook.class)
  public class TestNothing extends AbstractJUnit4SpringContextTests {
  
      @Autowired
      PersonRepository repo;
  
      @Test
      public void testInit() {
          Assert.assertTrue(repo.findAll().size() == 0 );
      }
  }
  
  =&gt; BeforeClassHook.beforeTestClass(): set up.
  =&gt; Process finished with exit code 0
  </code></pre>