msquitieri msquitieri -4 years ago 62
Java Question

Get reference to ApplicationContext with @ImportResource annotation?

I have the following class:

public class SocketMain extends SpringBootServletInitializer {
public static void main(String [] args) {
// ...

I want to get access to the application context in my
function so I can fetch one of my defined beans. I can't autowire it since you cannot autowire a static variable. Is there a way to get a reference to the applicationContext that is loaded with the

My fallback is to just load the applicationContext in
like so:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("path-to-application-context.xml");`

But I don't want to load it twice.

Thanks in advance!

Answer Source

This is the way to retrieve your application context in Spring and retrieve a bean. This should be placed in your main function

ApplicationContext ctx =, args);
SomeClass sc = ctx.getBean(SomeClass.class);

You should also be able to retrieve the context with @Autowired.

private ApplicationContext context;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download