Reputation: 319
I am newbie to spring and I am trying to modify my app to implement spring framework. My request is to create a new bean for every new request and then refer that bean later in the code, for setting the values to it from a singleton bean. I am trying to declare the bean as prototype and refer that bean in my singleton bean using lookup method. But my problem was when trying to get the created prototype bean later for setting the values, I see its creating new bean again when getting the bean.
@Component
public class PersonTransaction {
@Autowired
PersonContext btContext;
@Autowired
PersonMapper personMapper;
public void setPersonMapper(PersonViewMapper personMapper) {
this.personMapper = personMapper;
}
public PersonBTContext createContext() throws ContextException {
return btContext = getInitializedPersonBTInstance();
}
private PersonBTContext getContext() throws ContextException{
return this.btContext;
}
public void populateView(UserProfileBean userProfile) throws ContextException {
personMapper.populateView(userProfile,getContext());
}
@Lookup(value="personContext")
public PersonBTContext getInitializedPersonBTInstance(){
return null;
}
}
below is my prototype class
@Component("personContext")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PersonContext extends ReporterAdapterContext {
private List<Person> persons = null;
private Person person = null;
private List<String> attributes = null;
private boolean multiplePersons = false;
private boolean attributeSelected = false;
public boolean isMultiple() {
return multiplePersons;
}
public boolean isAttributeSelected() {
return attributeSelected;
}
private void setAttributeSelected(boolean attributeSelected) {
this.attributeSelected = attributeSelected;
}
// remaining getters/setters
}
when i call createContext from singleton PersonTransaction class, it should create new prototype bean and how can get the created prototype bean later by calling getContext() method (what i am doing by this.btContext is returning new bean again, I guess !!)..
Need help in getting the created prototype bean later for setting the values.
appreciate ur help..
Upvotes: 0
Views: 1248
Reputation: 44970
You want to create a request scoped bean, not a prototype scoped bean. Take a look at Quick Guide to Spring Bean Scopes which describes different bean scopes, including the request scope:
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public PersonContext personContext() {
return new PersonContext();
}
This should simplify your logic as long as you can discard the bean after the request is processed.
Upvotes: 1