Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring autowiring not working from a non-spring managed class

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 image 233
l a s Avatar asked Aug 21 '13 01:08

l a s


People also ask

Can I Autowire in non Spring class?

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.

Can I Autowire a POJO 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).


1 Answers

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); 
like image 129
Ashish Chaurasia Avatar answered Sep 22 '22 23:09

Ashish Chaurasia