4

Here is my email service

@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);
}

}

And I use JavaMailSenderImpl to implement MailSender

 <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>

to let spring recognize the @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" />

But it is said, @Async don't work in service method, right?

What should I do to implement it?

4

2 回答 2

0

@Async适用于所有@Component我也像你一样面临这个问题。客户端仍在等待电子邮件发送过程结束(不以异步方式运行)。由于这篇文章,

...我在同一个类中调用该方法。我相信这与Spring的代理机制有关。

现在我将@Async方法从同一个@Service类中分离出来。这符合我的问题。

于 2014-10-21T08:31:33.907 回答
0

尝试更换:

<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" />

<task:executor id="executorService" pool-size="10" />

<task:annotation-driven executor="executorService" />

它对我很有效

于 2014-06-09T21:30:52.617 回答