none knows https://stackoverflow.com/a/21969071 https://www.baeldung.com/spring-bean-scopes "when you need a new bean every time" generic answers without any examples It seems to me that when you're reasoning "it is not a singleton 100%" than it should be a prototype :D
What exactly do you mean by "prototype"? And what problem do you try to solve?
Hello. Forgot to share some thoughts regarding your question. First of all, DI may be used for getters, setters, parameters. So basically, you don't need to create prototypes via ApplicationContext manually. Your controller action method may receive injected brand new prototype object with parameters or call any other producer method. Not only controller is a start point for everything. There can be scheduled jobs, database triggers, some background threads with anything. Any web app is like simple java app + web. This means your spring app may start, calculate "2+2", print it to the console and exit. So, basically, you can do anything there. What's the purpose of prototype beans. Personally, I use them when I need abstract factory (or any other creational design pattern), when I need to introduce indirection when creating objects. Instead of creating Interface, Factory interface, Factory impl, and so on, I simply define Interface and Impl. And just inject it. No need to create that boilerplate factory impl code again. When you need to produce several implementations for single interface, @Qualifier comes into play. Inject desired object by bean interface+qualifier where you want. Another good usage is the ability to inject all known interface implementations in a list - this is very useful when working with plugin-like functionality, where you define one interface for plugin, and many implementations for doing some plugin-specific job. Usually this job is producing other objects: it works as factory of factories. One important thing about prototype beans is that they are beans. This means if you need a prototype bean to use other managed objects of your app, you can inject them in your prototype bean. For example, if you find out that your prototype bean should use some singleton service, you can inject it. Or if it needs to use a bean with session scope for example, you inject it, and you are sure that each instance of prototype bean created for some user will always refer to correct session scope dependency bean.
Обсуждают сегодня