这是我的电子邮件服务
@Service("mailService")
public class EmailService
{
@Autowired
private MailSender mailSender;
@Async
public void sendMail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
@Async
public void sendPreConfiguredMail(String to,SimpleMailMessage configuredMessage) {
SimpleMailMessage mailMessage = new SimpleMailMessage(configuredMessage);
mailMessage.setTo(to);
mailSender.send(mailMessage);
}
}
并使用JavaMailSenderImpl实现了邮件发送器
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="25"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
让Spring识别@Async
<mvc:annotation-driven />
<bean id="executorService" class="java.util.concurrent.Executors"
factory-method="newFixedThreadPool">
<constructor-arg value="10" />
</bean>
<task:executor id="threadPoolTaskExecutor" pool-size="10" />
<task:annotation-driven executor="executorService" />
<context:component-scan base-package="com.bistyle.lifelog" />
但是据说,@Async在服务方法中不起作用,对吗?
我应该怎么做来实现它?
2条答案
按热度按时间ni65a41a1#
尝试替换:
与
对我来说效果很好
mzillmmw2#
@Async适用于所有** @Component **。我和您一样也遇到了这个问题。客户端仍在等待电子邮件发送过程结束(不以异步方式运行)。由于this post,
... * 我是从同一个类中调用这个方法的。我相信这与Spring的代理机制有关。*
现在我将**@Async方法从同一个@Service**类中分离出来,这正好符合我的问题。