0

I know i can @Autowire spring context or any bean in my test classes. But is there any way to get the currently used context statically?

@SpringBootTest
class MyTest {

  @Autowire var applicationContext: ApplicationContext? // that's NOT what i want

  @Test
  fun myTest() {
    val result = HelperClass.staticFunction()
  }
}

and then:

class HelperClass {

  static public MyObject staticFunction( {
    return Some_spring_or_junit_static_class. 
           getCurrentSpringContextOrBean(nameOfBean)
  }
}

spring caches its contexs while running multiple tests. but is there any way to actually get the one currently used statically?

piotrek
  • 13,982
  • 13
  • 79
  • 165
  • 1
    Does this answer your question? [How to inject ApplicationContext itself](https://stackoverflow.com/questions/4914012/how-to-inject-applicationcontext-itself) – Rob Evans Oct 23 '20 at 12:33
  • Use `@DirtiesContext` to reload the Spring ApplicationContext after the execution of the test – Dirk Deyne Oct 23 '20 at 12:57
  • @RobEvans nope, the link shows instance level injection, not a static injection. i edited my question – piotrek Oct 23 '20 at 14:26
  • I'm curious why you want to do this in a test. It sounds bad test practice to me – Bart Oct 24 '20 at 08:42
  • To add to my previous comment. By using a static/global state to hold the ApplicationContext you can run into problems with concurrent tests. – Bart Oct 24 '20 at 08:44

1 Answers1

0

I don't think you can inject beans directly in a static class as it will be created before SpringBoot is instantiating beans. But you could set the bean in the static class using the @PostConstruct annotation.

@Autowired
public ApplicationContext applicationContext;

@PostConstruct
public void init() {
    HelperClass.setApplicationContext(applicationContext);
}

and

public class HelperClass {

    public static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        HelperClass.applicationContext = applicationContext;
    }

    public static Object staticMethod(String beanName) {
        return applicationContext.getBean(beanName);
    }
}