spring autowiring not working from a non-spring managed class
Solution 1:
You can use this way to use spring bean in non-spring bean class
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext) {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}
now you can get the applicationcontext object by getApplicationContext() this method.
from applicationcontext you can get spring bean objects like this:
ApplicationContext appCtx = ApplicationContextUtils.getApplicationContext();
String strFromContext = appCtx.getBean(beanName, String.class);
Solution 2:
Autowiring won't work because class ABC is not managed by Spring. You could make Spring manage ABC by using one of the @Component annotations (@Component, @Service, @Controller, etc) above the class definition, and then using context:component-scan in your application context XML, or go old school and just define the bean directly in your application context.
If for some reason you can't make Spring manage class ABC, you can load the application context in ABC using something like:
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
and then use:
XYZ someXyz = (XYZ) context.getBean("MyXYZ");
to manually set the bean value.