How to access spring ApplicationContext in static junit @BeforeClass method?

I tried to get it:

private static ApplicationContext applicationContext;
@Autowired
    public static void setApplicationContext(ApplicationContext applicationContext) {
        AuditorTest.applicationContext = applicationContext;
    }

But this does not work like all other attempts.

How to auto-install static ApplicationContext?

+4
source share
2 answers

You cannot use autwire spring beans for static. You should do this with an instance method instead, and let it assign the value to a variable static(which will work just fine):

@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
    AuditorTest.applicationContext = applicationContext;
}

But I do not think that this is what you want. I think you should annotate the test class with SpringJUnitRunnerand @ContextConfiguration, and then you can autwire ApplicationContextthere:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)  // configuration location
public class TestClass {
    @Autowired
    private ApplicationContext context;
}
+3
source

, , , . - .

. spring ApplicationContext.

. ApplicationContext, ClassPamlApplicationContext, bean, .

<code>
public class BaseTestCase {
    static {
        AppicationContext context = new ClassPathXmlApplicationContext("test-config.xml");  
             // Do what you want to do with the context
             // Probably store in static variable to access somewhere else
         }  
    }
</code>
0

All Articles