Monday, April 03, 2006

My bad, I've started to autowire with Spring

In a web application I have been writing recently I needed a way to initialise an embedded database and additionally setup some other resources.

This is usually ServletContextListener territory but since I am using a Spring Framework enabled database access layer I needed a method that gives me access to Spring's BeanFactory mechanisms. I could create a ServletContextListener that accessed the BeanFactory details from the ServletContext (as set by Spring's ContextLoaderListener) but then the order of the ServletContextListeners in the web.xml would become significant, so I didn't favour that approach.

I created a bean that implemented the Spring Framework's interfaces; ServletContextAware, BeanFactoryAware and InitializingBean. It therefore contains the methods; setServletContext(ServletContext servletContext), setBeanFactory(BeanFactory beanFactory) and afterPropertiesSet().

An InitializingBean is invoked by the BeanFactory immediately after the applicationContext.xml (containing the bean definitions) is finished processing.

So what I end up with is a class that has ready access to the ServletContext and BeanFactory and is invoked immediately after the ContextLoaderListener has finished initialisation.

In essence, this is equivalent to a Spring aware ServletContextListener. Great, this is exactly what I need. However this bean works exclusively by autowiring which is bad apparently! Jason Zhicheng Li in his article Twelve Best Practices For Spring XML Configurations lists autowiring as the number one thing to avoid when using Spring.

The reason this is bad is that my ServletContextListener style bean makes no appearance in the web.xml. The properties of this bean are set by introspection conducted by the application context and not by any explicit reference in the configuration file to the dependencies that get injected.

So to the casual observer it must look like it works by magic! It is argued that autowiring may reduce readability and maintainability. The problem is I'm not actually sure how I could accomplish this without using autowiring.


Mark McLaren said...

That's a stupid rule. Autowiring is great because it means less configuration XML to maintain and keep in sync.
Note: Comment imported. Original by Jason Carreira website: at 2006-04-04 20:01