msquitieri msquitieri -4 years ago 62
Java Question

Get reference to ApplicationContext with @ImportResource annotation?

I have the following class:

@SpringBootApplication
@ImportResource("classpath:path-to-application-context.xml")
public class SocketMain extends SpringBootServletInitializer {
public static void main(String [] args) {
// ...
}
}


I want to get access to the application context in my
main
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
@ImportResource
annotation?

My fallback is to just load the applicationContext in
main
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 = SpringApplication.run(SocketMain.class, args);
SomeClass sc = ctx.getBean(SomeClass.class);
sc.testRun();

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

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