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 Spring MVC based application and I don't see any exception while server start-up.
But I still see Class XYZ coming as null. Is it because of the fact that Class ABC is not instantiated by Spring Container?
In such scenarios, how do i make use of auto-wiring?
Thanks.
Like in a spring managed class, you can't autowire bean in non spring class as below. The above code won't work and you will get the below exception at runtime. The springBean will be null as autowire annotation won't work in non spring class.
The @Autowired annotation in spring automatically injects the dependent beans into the associated references of a POJO class. This annotation will inject the dependent beans by matching the data-type (i.e. Works internally as Autowiring byType).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With