A singleton service depends on a prototype-scoped bean, and every caller gets the same instance. Why, and how do you get a fresh one per use?
Prototype scope means a new instance per request to the container, and a singleton asks once, at construction. Inject an ObjectProvider and call getObject() each time you need a fresh instance. A scoped proxy also works, but on a prototype it creates a new target on every method call, which is rarely what you meant.
Answer
Short answer
The singleton is created once, so its dependencies are resolved once. Prototype scope gives a new instance each time the container is asked, but a constructor-injected field asks exactly one time. Inject ObjectProvider<T> and call getObject() wherever you need a fresh instance; avoid a scoped proxy here unless you understand that it fetches a new target on every method call.
Was this answer helpful?
Likely follow-ups
- Your request-scoped bean is used from an @Async method. What fails, and why does the proxy not help?
- Why do @Lookup methods not work on a bean returned from an @Bean factory method?
- The prototype bean opens a file handle in @PostConstruct. Who closes it, and how would you make that impossible to forget?
- How would you pass a per-call argument, such as a customer id, into the constructor of each new prototype instance?
Related questions
- A method with REQUIRES_NEW was meant to save an audit row even when the main transaction fails. When does it work, and when does it deadlock?hardAlso on spring5 min
- Startup fails with NoUniqueBeanDefinitionException after someone adds a second implementation. Do you reach for @Primary, @Qualifier or a list of beans, and which fix ages badly?mediumAlso on spring4 min
- Why does @Transactional sometimes do nothing at all, even though the annotation is right there?mediumAlso on spring4 min
- The inner service threw, you caught the exception in the caller, and then the commit failed with UnexpectedRollbackException. Why?hardAlso on spring5 min