Women in Technology

Hear us Roar



Article:
  Twelve Best Practices For Spring XML Configurations
Subject:   Autowiring
Date:   2006-01-31 07:22:08
From:   mattinger
In response to the first comment, I am inclined to agree with the author that autowiring should be avoided. In many cases, you're going to have more than one instance of a given bean type. Consider the simple, and most common case: declarative transaction management. In general, first you create the target object (assume we've defined the _serviceTemplate bean to be a ProxyFactoryBean with a TransactionInterceptor):




<bean id="_myService"
class="MyServiceImpl">
<property name="myDao">
<ref local="_myDao" />
</property>
</bean>


<bean id="myService"
parent="_serviceTemplate"
<property name="proxyInterfaces"
value="MyService" />
<property name="target">
<ref local="_myService" />
</property>
</bean>




Once you do this, there is no way to autowire properties of type MyService, just matching on the class. Matching by name, now forces you to follow patterns based on your bean id's. I see this is a bad practice, since bean id's can change, and should only be relevant at the IOC level.


Another example would be datasources. Consider a design where you assume your different services can be distributed. At deployment time, we've decided to provide datasource driven implementations of our DAO layer. The datasource for each dao may be entirely different, necessitating multiple datasource instances (each with a different bean name) to be available. Autowiring is no longer an option if you're using Spring's JdbcDaoSupport (or indirectly HibernateDaoSupport), which has a fixed property name for the datasource.


I find it helpful to explicitly state my injections, as there is never a doubt where anythign is coming from. Tool-wise it makes sense as well, because it's easy to generate a nice dependency graph from an explicitly wired spring config file set. Generating this when autowiring is enabled is not quite so easy.

Full Threads Newest First

Showing messages 1 through 1 of 1.

  • I'm sorry...
    2006-02-01 16:02:16  jhannes [View]

    ... but that is just dumb. :-)

    I think everyone agrees that you shouldn't use autowire when Spring will throw an exception! But would you ever do that anyway?

    When autowiring would be ambigous, you cannot use it, so there is really no point in recommending against autowiring - it ain't an option!

    Now: Is it really a good thing that both you DAO and your proxy are available for autowiring? You DAO shouldn't be visible at all! Use an inner bean definition or an autoproxy thingie, and your problem will go away.

    Regarding autowire by name: When you can be consistent, that is not a problem, but a solution.