25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13 ■ Adding E-mail and Scheduling Tasks<br />

@Service<br />

public class EmailService {<br />

@Autowired<br />

private MailSender mailSender;<br />

public void send(String from, String to, String subject, String message) {<br />

sendEmail(from,to,subject,message);<br />

}<br />

@Async<br />

public void sendAsync(String from, String to, String subject, String message) {<br />

sendEmail(from,to,subject,message);<br />

}<br />

}<br />

private void sendEmail(String from, String to, String subject, String message){<br />

SimpleMailMessage mailMessage = new SimpleMailMessage();<br />

mailMessage.setFrom(from);<br />

mailMessage.setTo(to);<br />

mailMessage.setSubject(subject);<br />

mailMessage.setText(message);<br />

mailSender.send(mailMessage);<br />

}<br />

Listing 13-5 shows another method named sendAsync, which is actually the same as the send method; the only<br />

difference is that it is annotated with the @Async annotation. This will tell the <strong>Spring</strong> container to treat this<br />

method asynchronously when it’s called. But how do you tell the <strong>Spring</strong> container that you are going to use this<br />

Async annotation? Take a look at Listing 13-6, which shows the new namespace you are going to use:<br />

.<br />

Listing 13-6. mydocuments-context.xml<br />

<br />

<br />

<br />

<br />

<br />

<br />

187

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!