1.失效的代码如下
解决办法:单独定义一个异步类来进行处理
运行结果如下
package demo.controller;
import demo.sync.MemberServiceSync;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class MemberService {
@Autowired
private MemberServiceSync memberServiceSync;
@RequestMapping("/addMember")
public String addMember(){
log.info("模拟插入到数据库0001");
//发送短信
/* new Thread(new Runnable(){
@Override
public void run(){
sms();
}
}).start();*/
memberServiceSync.sms();
log.info("用户注册成功0004");
return "用户注册成功";
}
/* @Async
public String sms(){
log.info("<0002>");
try{
log.info("正在发送短信");
Thread.sleep(3000);
}catch(Exception e){
}
log.info("<0003>");
return "发送短信成功";
}*/
}
package demo.sync;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class MemberServiceSync {
@Async
public String sms(){
log.info("<0002>");
try{
log.info("正在发送短信");
Thread.sleep(3000);
}catch(Exception e){
}
log.info("<0003>");
return "发送短信成功";
}
}
package demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//@ComponentScan("demo")
@EnableScheduling
@EnableAsync
@MapperScan("demo.mapper")
public class demoApplication {
public static void main(String[] args){
SpringApplication.run(demoApplication.class);
}
}