Expert Spring MVC and Web Flow

(Dana P.) #1
private boolean active = false;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}

public void activate() {
if (active) {
throw new IllegalStateException("Already active");
}
active = true;
sendActivationEmail();
}

private void sendActivationEmail() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(email);
msg.setSubject("Congrats!");
msg.setText("You're the best.");
mailSender.send(msg);
}
}

The AccountPOJO in Listing 3-4 has a method called activate()that sets the account
instance as active and then sends an activation email. Clearly it needs an instance of
MailSender, as it doesn’t create one itself. We will use the code in Listing 3-5 to ask Spring
to inject this dependency, based on the previous abstract accountdefinition.

Listing 3-5.Example Dependency Injection of Existing POJO

package com.apress.expertspringmvc.chap3;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class DependencyInjectionExistingPojo {

public static void main(String[] args) throws Exception {

34 CHAPTER 3 ■SPRING MVC APPLICATION ARCHITECTURE

Free download pdf