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"

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 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.

Autowired Annotation

There is an option to annotate a setter with @Autowired. This means that Spring will search the context for a bean that matches and set it in there.

public class Bean
    private InnerBean innerBean;
    private InnerBean2 innerBean2;

    public void setInnerBean(InnerBean innerBean)
        this.innerBean = innerBean;

    @Autowired(required = false)
    public void setInnerBean2(InnerBean2 innerBean2)
        this.innerBean2 = innerBean2;

Your spring xml must also have context:component-scan configured.

<context:component-scan base-package="com.magicmonster.example" />

Published: Wednesday, 16 August 2006