Spring's BeanFactory for Dependency Injection

XML configuration

Bean XML namespace header

The following is a sample header you can use at the top of your XML files. The namespace should help your editor automatically complete element and attribute names.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    

Beans can be configured or wired up using an XML file. e.g.

  <bean id="userService" class="com.magicmonster.intranet.service.UserServiceImpl">
    <property name="dao" ref="userDao"/>
  </bean>
  <bean id="userDao" class="com.magicmonster.intranet.dao.JDBCUserDaoImpl"/>
    

If you program to Interfaces, then you can switch implementation classes using the configuration file. The classes specified must adhere to the javabeans standard of getters and setters.

Factory Beans

Spring also knows about some special beans that implement FactoryBean, and comes with several implementations. When they are used to build up an instance of another bean, the instance itself is not used, but its getObject() method is called and the Object returned is used instead.

See javadocs: NB: A bean that implements this interface cannot be used as a normal bean. A FactoryBean is defined in a bean style, but the object exposed for bean references is always the object that it creates.

Published: Wednesday, 16 August 2006