java – When to and When not to use IOC/Dependency Injection? – Education Career Blog

I am working with several Spring MVC web applications and I use the getter/setter dependency injection and configure all my beans in my app-servlet.xml file.

I believe that I am following convention with most of the properties and beans that I am injecting into my controller beans such as my DAO’s and other beans that I have specified in either my applicationContext.xml or in the app-servlet.xml

As my applications have been getting more complex and larger, the beans in these files have been filling up with more properties that are being injected.

My question is, where is the line, or what is the convention on what should be injected, and what should be specified as an instance field/variable in the controller.

Sometimes I am faced with a situation if I am going to specify the value for a field in the actual controller, or if I am going to inject the value into that controllers bean.

For example, I am using velocity template library for sending my emails. There is a path to the directory of my Velocity Templates. I am faced with doing one of the following.

In my Controller I could specify the value

 private String basePath = "/path/to/velocity/templates";

Or in my Controller bean I could inject the same value into that controller

<property name="basePath" value="/path/to/velocity/templates"/>

and in my class I would have the getters/setters for this injected value.

I am not sure where to draw the line for each.

,

I normally inject based on:

  1. whether I need to change this value per environment/deployment (e.g. using a PropertyPlaceholderConfiguration).
  2. whether I need to mock something out for testing.
  3. whether someone else is likely to consume this class in the future and want to do one of the above.

If you’re not careful, then your configurations can become a mass of injected properties (I prefer to use constructor arguments so I can guarantee correct instantiation, but that’s another story). The above guidelines work well in limiting the number of injections whilst permitting flexibility.

,

Do NOT plan for “flexibility” up front. Usually you ain’t gonna need it.

When the time comes and you really need it, then refactor your code.

Leave a Comment