0

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.

daedsidog
  • 1,732
  • 2
  • 17
  • 36
gursahib.singh.sahni
  • 1,559
  • 3
  • 26
  • 51
  • In this instance it is the same as Request scoped which is the norm. EntityManager is not thread safe so you need to make sure that the same instance doesn't get passed to multiple threads. Request scoped will take care of that just fine. Prototype scoped says to never create the same instance twice but it's overkill for the use case. – K.Nicholas Dec 19 '18 at 02:07
  • So you mean for every request we need a new instance of EntityManager? Because it’s not threadsafe. Yes, the prototype scope def seems like an overkill, so how do we deal with such situations? – gursahib.singh.sahni Dec 19 '18 at 02:19
  • https://stackoverflow.com/questions/10380539/persistencecontext-entitymanager-thread-safety-in-spring-and-java-ee – K.Nicholas Dec 19 '18 at 04:00
  • @K.Nicholas I think I was looking at this answer. https://stackoverflow.com/questions/24643863/is-entitymanager-really-thread-safe#answer-24644435 Probably a container injected EntityManager is something I should be looking forward to if I go for the stateless spring bean. Thoughts? – gursahib.singh.sahni Dec 19 '18 at 15:04

0 Answers0