这次来看看Spring提高的一些有用过的JEE中使用到的功能,如 发送Email, 执行定时任务...
先来看看发送Email吧, 在Spring中发送Email是很简单的,使用Spring提高的MailSender和MailMessage就可以了,配置代码如下:
<?
xml version="1.0" encoding="UTF-8"?><!
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd" ><
beans><value>smtp.163.com</value>
<props>
<!-- 如果要使用用户名和密码验证,这一步需要 -->
<!-- 简单的message -->
<!-- 测试发送的类 -->
</
beans>上面的配置好以后就可以直接发送了, 看看TestSenderMail.java的代码:
MILY: ´Courier New´, Courier">package test.mail;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
public class TestSenderMail {
private MailSender mailSender;
private SimpleMailMessage mailMessage;
public TestSenderMail() {
}
public SimpleMailMessage getMailMessage() {
return mailMessage;
}
public void setMailMessage(SimpleMailMessage mailMessage) {
this.mailMessage = mailMessage;
}
public MailSender getMailSender() {
return mailSender;
}
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage(mailMessage);
//设置email内容,
message.setText("测试Spring 发送Email.");
try {
mailSender.send(message);
} catch (MailException e) {
// TODO Auto-generated catch block
System.out.println("O . 发送Email失败了....");
e.printStackTrace();
}
}
}
很简单吧. 下面是测试类: TestApp.java
package test.mail;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext(
"test/mail/mail.xml");
TestSenderMail sender = (TestSenderMail) context
.getBean("testMailSender");
sender.sendMail();
}
//抛出如下异常,是瑞星监控的问题,关闭就可以了
/**
* DEBUG SMTP: QUIT failed with 250 O . 发送Email失败了....
* org.springframework.mail.MailSendException: Could not send mails: 354
*
* com.sun.mail.smtp.SMTPSendFailedException: 354
*
* at
* com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
* at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1215) at
* com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:586)
*/
}
呵呵, 现在就可以发送Email了.