原理篇
https://blog.51cto.com/u_3631118/3121465
原代码
@EnableAsync
@Service
public class ServiceImpl implements Service {
@Async
@Override
public void testAsync() {
Thread.sleep(10000);
}
@Override
public void test() {
testAsync();
}
这里虽然加了@EnableAsync和@Async,但是异步请求依然没有生效
解决方案:
方法一:
同一个类中调用需要先获取代理对象,也就是手动获取对象
@Override
public void test() {
ServiceImpl bean = SpringApplicationUtils.getBean(ServiceImpl.class);
bean.testAsync();
}
方法二:
不同的类调用,直接注入即可
@EnableAsync
@Service
public class ServiceImpl implements Service {
@Async
@Override
public void testAsync() {
Thread.sleep(10000);
}
}
@Service
public class DemoService {
@Autowired
private Service service;
public void test(){
System.out.println("开始");
service.testAsync();
System.out.println("结束");
}
}
SpringApplicationUtils
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringApplicationUtils implements ApplicationContextAware {
private static ApplicationContext ctx = null;
public SpringApplicationUtils() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (ctx == null) {
ctx = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
public static <T> T getBean(Class<T> requiredType) {
return ctx.getBean(requiredType);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return ctx.getBean(name, requiredType);
}
}