Reputation: 1023
I have a spring based webapp and I also have a background process. From inside the background process, I would like to be able to access spring beans. I normally retrieve spring beans by using:
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object mySpringBean = context.getBean("mySpringBean");
The problem is that my background process is not servlet based and does not have access to the servletContext. The background process is triggered by a proprietary task execution program. This task execution program uses Class.forName to instantiate my background process and I am not permitted to modify the task execution program.
Is it possible for my background process to access spring beans? If so, how?
Upvotes: 0
Views: 2854
Reputation: 6879
First off, my solution here is not ideal. Before using this, think about the architecture of your application, more than likely, you can make a structural change to get access to the context.
If you have multiple contexts you are maintaining, you will obviously need to add a bit more logic in here to sort them out.
You can create an ApplicationContextAware bean, and access your context via a static:
@Component
public class SpringApplicationContext implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CONTEXT = applicationContext;
}
public static <T> T getBean(Class<? extends T> beanClass) {
return CONTEXT.getBean(beanClass);
}
protected static ApplicationContext getContext() {
return SpringApplicationContext.CONTEXT;
}
}
Another option, is if you have a way to register the context in your background process, you can do that in the setApplicationContext method.
Upvotes: 4
Reputation: 21564
Try using a org.springframework.context.support.ClassPathXmlApplicationContext for loading the Spring context :
ApplicationContext context = new ClassPathXmlApplicationContext("/path/to/applicationContext.xml");
Upvotes: 3
Reputation: 120858
How about this?`
ApplicationContext context = new ClassPathXmlApplicationContext("/spring-activemq/spring-activemq-producer-nio.xml");
All you have to do is specify where your XML is
Upvotes: 1
Reputation: 3250
Your background process must manually create the context. Typically this is done once during process initialization.
Something like:
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "appContext.xml" }, true );
Upvotes: 0