Reputation: 1299
Hi I am unable to autowire my bean inside another bean which is instantiated using a factory method.
class A{
private String name;
//getters and setters for name
}
class B{
@Autowired
private A x;
private B(String Gender, String jobProfile){
String name = x.getName();
//some code
}
public static getInstance(String Gender,String jobProfile){
//some code for instantiation.
}
}
Now when i create the instance of class B using factory method, from some different class. Autowiring does not happens, it returns NULL i.e. x is coming as null. Hence i am getting null pointer exceptions when calling getName on this
Have you any solution for it ?? or i am doing somethign wroing ??
Upvotes: 3
Views: 11360
Reputation: 4342
In the @Autowired documentation is said that fields are autowired after object construction.
So in your code Spring has not jet injected x
when you try to use x.getName()
in constructor.
You have several options:
Upvotes: 1
Reputation: 8282
When you create an object by new, autowire\inject don't work...
as workaround you can try this:
and create an istance in this way
context.getBean("myBean");
PROTOTYPE : This scopes a single bean definition to have any number of object instances.
Config
<bean id="a" class="..." >
<bean id="b" class="..." scope="prototype">
<bean id="factory" class="..." >
Factory class
public class Factory implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext = applicationContext;
}
public B createClass(){
context.getBean("b");
}
public B createClass(Object... args){
context.getBean("b",args);
}
}
in this way Autowired annotation works fine.
As Javadocs say getBean ..
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use if creating a prototype using explicit arguments to a
* static factory method. It is invalid to use a non-null args value in any other case.
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
Upvotes: 1