二、Spring集成
1、Mail
(1)SimpleMailMessage
l 创建消息
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("me@mail.org");
msg.setTo("you@mail.org");
msg.setCc(new String[] {"he@mail.org", "she@mail.org"});
msg.setBcc(new String[] {"us@mail.org", "them@mail.org"});
msg.setSubject("my subject");
msg.setText("my text");
(2)MailSender
l 定义消息发送者
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host"><value>smtp.mail.org</value></property>
<property name="username"><value>joe</value></property>
<property name="password"><value>abc123</value></property>
</bean>
l 发送消息
MailSender sender = (MailSender) ctx.getBean("mailSender");
sender.send(msg);
2、调度(scheduling)
(1)调度程序
l 内建支持:
Ø Java 2 Timer:Timer、TimerTask
Ø Quartz:Schedulers、JobDetails、Triggers
(2)ScheduledTimerTask
l 我们想要运行的任务
public class MyTask extends TimerTask {
public void run() {
// do something
}
}
<bean id="myTask"
class="...scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<bean class="eg.MyTask"/>
</property>
<property name="delay"><value>60000</value></property>
<property name="period"><value>1000</value></property>
</bean>
包装java.util.TimerTask调度的Bean
(3)TimerFactoryBean
l 创建调度器
<bean id="scheduler"
class="...scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list><ref bean="myTask"/></list>
</property>
</bean>
创建一个java.util.Timer对象
l 在Bean创建时,Timer开始运行
3、JNDI
(1)JndiTemplate
l 使用JndiTemplate
Properties p = new Properties();
p.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
p.setProperty("java.naming.provider.url",
"jnp://localhost:1099");
JndiTemplate jndi = new JndiTemplate(p);
Properties env = jndi.getEnvironment();
try {
jndi.bind("Something", something);
Object o = jndi.lookup("Something");
jndi.unbind("Something");
}
catch(NamingException e) {
...
}
(2)JndiObjectFacroryBean
l 使用Bean替代loopup
<bean id="jndiTemplate"
class="org.springframework.jndi.JndiTemplate">
<constructor-arg>
<props>
<prop key="java.naming.factory.initial">
org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.provider.url">jnp://localhost:1099</prop>
</props>
</constructor-arg>
</bean>
<bean id="something"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate"><ref bean="jndiTemplate"/></property>
<property name="jndiName"><value>Something</value></property>
</bean>
Object o = ctx.getBean("something");