Issue
This is probably a beginner question, and has to do with how the java serves a website. I come from a PHP background, where for each request previous state is cleared.
Why is it that when I define a bean, like below, the same object hash is returned on page refresh?
@Bean
public BreadCrumbs breadCrumbs()
{
List<AssemblerInterface> assemblers = new ArrayList<AssemblerInterface>();
assemblers.add(new BlogPostAssembler());
return new BreadCrumbs(new RenderStrategy(), assemblers);
}
In my controller:
System.out.println(breadCrumbs.hashCode());
On each page request, the same hashcode is returned:
817233364
817233364
817233364
817233364
817233364
817233364
817233364
817233364
817233364
817233364
817233364
And the state of the Breadcrumbs component accumulates (showing the same items over and over). The question is how do avoid it?
Solution
What @syedAmmar wrote is correct, but not complete.
Making your breadCrumbs
a prototype is only part of the solution. it means it will be created each time it is called, and not only once.
However, it is not enough since your controller is a singleton, meaning it is created only once, and calls the breadcrumbs bean only once. This is why you get different instance on separate controllers, but not on separate calls.
to resolve that, you need your singleton controller to get a different prototype on each request.
One way to do that is using Spring's ObjectFactory
interface:
@Controller
public class SomeController {
private ObjectFactory<BreadCrumbs> breadCrumbsFactory;
@Autowired
public SomeController(ObjectFactory<BreadCrumbs> breadCrumbsFactory) {
this.breadCrumbsFactory = breadCrumbsFactory;
}
public void something() {
BreadCrumbs breadCrumbs = breadCrumbsFactory.getObject(); // this will give you a different instance on each call
}
}
You can read more about it on this guide
Answered By - Nir Levy