Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

java - @Autowired fields null for beans created in a loop (second bean onwards)

I am creating beans by calling the method getAction in a loop.

...
ArrayList<Action> actions = new ArrayList<Action>();
for(int i=0; i<actionClasses.length; i++)
{
    actions.add(getAction((Class<? extends Action>) Class.forName(actionClasses[i])));
}
...

@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Action getAction(Class<? extends Action> clazz) throws Exception
{
    return clazz.newInstance();
}

The issue is that only the first bean created is autowired. The rest of the beans created have null values for fields supposed to be autowired. However, things started working when the newInstance was replaced with createBean as below.

...
for(int i=0; i<actionClasses.length; i++)
{
    actions.add(context.getAutowireCapableBeanFactory().createBean((Class<? extends Action>) Class.forName(actionClasses[i])));
}
...

Can anybody explain why this is happening?

Note: all the action classes are different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...