I have a class (Class ABC) that\'s instantiated by calling the constructor. Class ABC in turn has a helper class (Class XYZ) injected using auto-wired.
Ours is a Sp
You can use this way to use spring bean in non-spring bean class
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
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 = (String) appCtx.getBean(beanName);
You can annotate ABC
class with @Configurable
annotation. Then Spring IOC will inject XYZ
instance to ABC
class. It's typically used with the AspectJ AnnotationBeanConfigurerAspect
.
Correct: You can't just call new
on a class and get it all wired up; Spring has to be managing the bean for it to do all of its magic.
If you can post more details on your use case, we may be able to suggest useful options.
In response to the answer provided by @Ashish Chaurasia, would like to mention that the solution is partial. The class ApplicationContextUtils
should also be a spring bean in order for spring to invoke the below code.
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
@Component
at the top of the class would make the solution complete. Also, there is one more alternative of doing it with the @Autowired
annotation.
@Component
public class ApplicationContextProvider {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Autowired
public void setContext(ApplicationContext context) {
ApplicationContextProvider.context = context;
}
}
The getBean
method can now easily be accessed by -
ApplicationContextProvider.getApplicationContext().getBean("myBean");