Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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?

like image 678
Volodymyr Levytskyi Avatar asked Apr 07 '15 16:04

Volodymyr Levytskyi


1 Answers

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;
}
like image 160
Rohit Jain Avatar answered Nov 09 '22 23:11

Rohit Jain