Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing complexity in a dependency-injected app with a large number of beans

I'm working on an Spring application which has a large number of beans - in the hundreds - and it's getting quite cumbersome to use and document.

I'm interested in any experience you have with DI-enabled apps with a large number of beans which would aid maintainability, documentation and general usage.

Although the application is Spring-based with a couple of context files, I'm open to listening about suggestions regarding any DI container and about DI in general as well.

like image 764
Robert Munteanu Avatar asked Jun 12 '09 11:06

Robert Munteanu


2 Answers

You can use component scan and autowiring features to dramatically decrease the amount of Spring XML configuration.

Example:


<beans>
  <!-- Scans service package looking for @Service annotated beans -->
  <context:component-scan base-package="my.root.package.service"/>

</beans>

Your service classes must be annotated in order to be automatically scanned:


package my.root.package.service;

@Service("fooService") public class FooServiceImpl implements FooService{

}

You can also use the @Autowired annotation to tell Spring how to inject the bean dependencies:


package my.root.package.service;

@Service("barService")
public class BarServiceImpl implements BarService{
    //Foo service injected by Spring
    @Autowired
    private FooService fooService;

    //...
}

like image 149
Wilson Freitas Avatar answered Sep 22 '22 14:09

Wilson Freitas


I found the following to be of use:

  1. split your Spring configurations into multiple standalone configurations, and use Spring's import facility to import configuration dependencies (see here, section 3.2.2.1). That way you have a set of configurations that you can combine or disassemble as required, and they are all self-dependent (all the dependencies will be explicit and referenced)
  2. Use an IDE that is Spring-aware, and allows you to navigate through the configurations via point-n-click on beans (references/names, to-and-from source code). Intellij works very well at this (version 7 and beyond, I think). I suspect Eclipse would do something similar.
  3. Revise what you're injecting where. You may want to refactor multiple bean injections into one composite or 'meta' bean, or a larger component. Or you may find that components you once thought you'd need to inject have never changed, or never demanded that injectability (for testing, implementing as strategies etc.)

I used to work with a huge Spring installation, with hundreds (thousands?) of beans. Splitting the configurations up made life a lot more manageable, and simplified testing/creating standalone processes etc. But I think the Intellij Spring integration that came with Intellij made the most difference. Having a Spring-aware IDE is a major timesaver.

like image 45
Brian Agnew Avatar answered Sep 20 '22 14:09

Brian Agnew