Java – How to load a bean into Spring MVC’s application context

javaspringspring-mvc

As I understand it, Spring MVC application has two distinct contexts, the application context and the web context, which are controlled by applicationContext.xml and dispatcher-servlet.xml, respectively.

Inside my controllers, how do I go about loading a bean into either of these contexts?

Note that I am aware of Getting Spring Application Context. That would answer my question for a stand alone application. Where I would use a factory to load the application context from the xml file, but this seems like the wrong way to go about loading beans in Spring MVC.

Best Answer

Matt is absolutely correct. You should not need with any kind of bean-loading/instantiating code in your MVC application, otherwise you're doing something wrong. You define your beans inside the according spring XML configuration files.

<bean id="pinboardServiceTarget" class="com.lifepin.services.PinboardService">
    <property name="pinboardEntryDao" ref="pinboardEntryDAO"/>
</bean>
...
<bean id="pinboardEntryDAO" class="com.lifepin.daos.PinboardEntryDAO">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

Your PinboardService class (this is just from an application I wrote recently) will have a property IPinboardEntryDAO like

public class PinboardService implements IPinboardService{
  private IPinboardEntryDAO pinboardEntryDao;

  ...

  public void setPinboardEntryDAO(IPinboardEntryDAO dao){
     this.pinboardEntryDao = dao;
  }

  public IPinboardEntryDAO getPinboardEntryDAO(){
    ...
  }

  ...
}

public class PinboardEntryDAO implements IPinboardEntryDAO{
   ...
}

Note that inside the the PinboardService class I'm using the DAO interface, not the implementation itself, while in the configuration I'm then injecting the real implementation PinboardEntryDAO. This is a very good practice for separating the different layers (presentation, service and data layer).