Sending email using spring in a new topic

One of the functionality of the application that I am developing is that an email is sent every time a user receives his account registered in our system. Sending email from a Java application is easy, especially when using Spring. I am using JavaMailSenderImpl and SimpleMailMessage from Spring and it works fine.

But I need to send email to a new stream so that communication with the SMTP server does not slow down the rest of the application processes. The problem is that when I call

MailSender.send()

from a new stream, an email message is not sent, in contrast, when sent to the same stream. I tried with Spring annotation @Async, Spring Executor and plain old java.lang.Thread , but it does not work.

Is it possible to send email asynchronously in java using spring? Has anyone had a similar problem with this? If necessary, I can send code samples.

Tpx

+5
source share
4 answers

It should work.

You need to tell Spring that it should pay attention to your @AsyncAnnotation by:

<task:annotation-driven />

And there are some limitations with which you need to be respected:

  • Spring bean
  • Spring Bean ( Spring AOP).
+3

1) spring. xsd spring 3.0. xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd

2) spring .

<!--  Executor for the methods marked wiht @async annotations --> 
<task:executor id="asyncExecutor" pool-size="25" /> 

3) spring

<!--  Configuration for the Runtime --> 
<task:annotation-driven executor="asyncExecutor" /> 

, spring.

, , @Async.

, @async, be spring.

+3

, , , , . , ( @Async, , - ) , , .

, @Async , , , . , , , @Transactional @Service, Session EntityManager; , , , @Async @Transactional , Session EntityManager, .

TL DR Provide an exception handler to throw exceptions that will be swallowed by the asynchronous stream otherwise, or use the large try/ catchbody method for debugging @Async. You will probably see some kind of exception, and you will need to take the right actions to avoid this.

0
source

You need to enable the function in Spring:

@EnableAsync
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
0
source

All Articles