Search code examples
javaspringdependency-injectioninversion-of-controlspring-framework-beans

Proper way to put spring beans


We are using java beans for dependency injection. However, we have found that the beans were not created in a proper way. My question is: what's a proper way to organize those beans? I have read many books or online posts about it but not clear about the solutions. Let me give you an example here. For example, I have a bean called TestBeanAand I put it in moduleA. I have another moduleB which references moduleA, so I can use TestBeanA in moduleB.

1)1st issue is: Now I have another moduleC which is in a different service or package. In order to use TestBean inmoduleC, I can add moduleA as a dependency in moduleC then use TestBean there? Is this a good approach? or just create a new bean in moduleC?

2) 2nd issue is that: now if I have another bean TestBeanB in moduleB. How can i use this bean in moduleA? or putting TestBean in moduleB was wrong, and it should be put in moduleA as well?


Solution

  • Each bean holds logic or data that preferably isn't duplicated in your system, also most beans follow the singleton pattern, so it must be unique in the system

    When a bean is a singleton, only one shared instance of the bean will be managed

    Thefore you should include module's bean in a new/updated module and not create redundant beans