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...)-

1

There are 1 best solutions below

2
Radu Sebastian LAZIN On

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 :)