Spring dynamic injection, factory-like pattern

余生长醉 提交于 2019-12-02 18:45:33

If you want some member of your class to be dynamically initialized\populated on every call to the corresponding getter, you can try the Lookup Method Injection. Read pp. 3.3.4.1 here.

So even if the class that contains the dynamic member was created in scope=singletone (the default for spring bean container) every time you will accessthe field that has a lookup method assigned, you will get an appropriate object according to the business logic implemented inside the lookup method. In your case the list is an interface so you can easily implement the validation inside your lookup method and return a validated list.

Edit:

I found better example in Spring documentation - I think it is very clear. Take a look at "3.4.6.1 Lookup method injection"

When you configure the Main class assign a lookup method to its List member - it will be called whenever you need a new instance of the List bean.

Good luck!

Yves Martin

Spring is designed for re-usable component injection, not for business data manipulation and injection.

Indeed some data are used in dependency injection, but only to configure components behavior, not to create business data holder.

By the way, the following option may be used in your case: thanks a BeanFactory with BeanFactoryAware interface and the use of scope="prototype", you can generate a bean by invoking getBean() like in that example or from that other question: creating bean on demand.

An alternative option if you have a limited number of beans to prepare is to use generic bean creation the same way lacking beans are mocked

Now consider that Spring never garbage collects beans in its Context. So it is risky for memory consumption to create Spring beans to hold business data.

If your aim is different (I hope so), maybe you are trying to implement by your own a multi-tenant support. Spring provides tenancy in case you have different business context to implement with specific components or behaviors.

Sounds like a user can choose 1..N graphs of Objects and you only want to load the one that the user selects at runtime. If the graphs are known at design time but the user just chooses the one they want then it sounds to me like what you have is a bunch of ApplicationContexts and you only want to load the one ApplicationContext that the user selects at runtime. So why not just define the set of ApplicationContexts and then just instantiate the right one at runtime. Since Spring supports Java Config it might make sense to define these configs as Java classes so you can get inheritance and avoid cutting/pasting any code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!