I was having a look at a codebase at my company today morning and to me, it wasn't something very obvious. I have worked with Spring MVC enterprise projects but in my experience, I never had to use the prototype Scope. I have seen its usage in some classes previously but this was something unusual to me.
Codebase
@RestController
@Scope("prototype") // this is set due to BaseEntity.setEntityManager
@RequestMapping(path = "/baseurl")
public class SampleController {
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
BaseEntity.setEntityManager(entityManager);
}
@RequestMapping (path = "/some-path")
public void getThis() {}
}
Here, the comment which says that this is set due to BaseEntity.setEntityManager
is not very clear that why it was done. Why I find it weird?
Because for every incoming request there would be a new Object of this controller in JVM. Moreover, this is done for ALL the @RestController
classes. So, logically someday with a high volume of requests, the system might throw OOM. Does it even adhere to best practices?
Provided Scope implies that the dev wanted to maintain the state. But how is it related to the @PersistenceContext
?
I couldn't find any evidence to as to why is it done. So, any leads to what can be the reason would be really helpful.