Spring's BeanFactory for Dependency Injection

Published: Wednesday, 16 August 2006
Last modified: Wednesday, 3 June 2020

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 autocomplete 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. with setters

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

or using constructors:

<bean id="userService" class="com.magicmonster.intranet.service.UserServiceImpl">
    <constructor-arg name="dao" ref="dao"/>
</bean>

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 beans that implement FactoryBean. They are used for creating instances, hence the name FactoryBean. The instance itself is not used, but its getObject method is called and the Object returned is used instead.

See Javadocs:

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;

    @Autowired
    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" />