Expert Spring MVC and Web Flow

(Dana P.) #1

Dependency Injection for the Domain Model


As you probably know, Spring does an excellent job of creating POJOs and wiring them
together. This works well when the object is actually created and initialized by Spring, but
this isn’t always the case with objects in the domain model. These instances can come from
outside the ApplicationContext, for instance loaded directly by the database. How do we
inject these objects with their dependencies before they enter the application?
If you have an object instance already constructed, but you would like Spring to wire that
object with any dependencies, you will need an instance of a AutowireCapableBeanFactory.
Luckily, XmlBeanFactoryhappens to implement that interface. Listing 3-3 illustrates how to
wire an existing POJO with dependencies.


Listing 3-3.Bean Definition for Wiring an Existing POJO


<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">



<bean id="account" abstract="true"
class="com.apress.expertspringmvc.chap3.Account">
<property name="mailSender" ref="mailSender" />
</bean>

<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.example.com" />
</bean>


The preceding bean definition specifies one abstract bean definition for an Account
object. An Accounthas a MailSenderas a property. We then define the MailSenderas the sec-
ond bean in this bean definition. Note we use abstract="true"to ensure it will never be
created inside the container.


Listing 3-4.Simple POJO Requiring an External Resource


package com.apress.expertspringmvc.chap3;


import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;


public class Account {


private String email;

private MailSender mailSender;

CHAPTER 3 ■SPRING MVC APPLICATION ARCHITECTURE 33
Free download pdf