0

What i am looking for is getting the spring application context somehow along the following lines :

ApplicationContext ac = SomeSpringClass.getCurrentContext() 
// As you may notice, the SomeSpringClass is not real
// it's just what i am looking for as an example

other solution are welcome as long as the do not use the classic ways to get the application context (@Autowired, implementing ApplicationContextAware, Constructor injection, Setter injection...)-

  • You can use the return value of `SpringApplication.run(args);` – Unmitigated Jul 18 '23 at 15:29
  • thanks @Unmitigated, this solution could be used whenever i need the current spring context ? or i need to get it and store it somewhere when the first time the application runs ? – Hassen Gaaya Jul 18 '23 at 15:38
  • 1
    You would store it on application startup. Why do you want to avoid Autowired though? – Unmitigated Jul 18 '23 at 15:39
  • Sometimes i need to access the application context while debugging the code and i find it disappointing to have to inject it through @Autowired every time i need it when debugging – Hassen Gaaya Jul 18 '23 at 15:45

1 Answers1

0

You could do something like this (a bean than has a static reference to the context):

@Component
public class StaticSpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext context = null;

    private static void setContext(final ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    @EventListener
    public static void onApplicationEvent(final ApplicationReadyEvent event) {
        setContext(event.getApplicationContext());
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        setContext(applicationContext);
    }

}

and then anywhere in your code when your app is running you can:

StaticSpringApplicationContext.getContext()

this bean will initialize the static variable as soon as the application is loaded and this is it's only purpose :)

  • thanks radu-sebastian-lazin, but it's not what i'm looking for. as i discussed with @Unmitigated, i need to access it during debug time so it's somehow an overkill to create this class – Hassen Gaaya Jul 18 '23 at 15:49
  • Well this will work in debug mode as well, and you can just copy paste it in your project and after your debug is done just remove the `@Component` and it won't be instantiated or maybe add a `@Conditional` – Radu Sebastian LAZIN Jul 19 '23 at 01:47