简体   繁体   中英

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

I tried to get it by:

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

But it doesn't work as all other attempts.

How to autowire static ApplicationContext ?

You can't autowire spring beans on static methods. You've to make it an instance method instead, and let it assign the value to static variable (that will work fine):

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

But I don't think this is what you want. I guess you should annotate the test class with SpringJUnitRunner , and @ContextConfiguration , and then you'll be able to autowire the ApplicationContext there:

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

Probably you might have figured out a workaround by now. May help someone else here.

I ran across the similar issue. Most of the spring framework options provided does not allow static access of ApplicationContext.

The workaround is simple. Create your own ApplicationContext using ClassPathXmlApplicationContext using the bean configuration but statically.

<code>
public class BaseTestCase {
    static {
        ApplicationContext 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM