在一个方法中异步执行另外一个方法 无需等待
时间: 2023-08-09 21:05:17 浏览: 46
可以在一个方法中异步执行另外一个方法,无需等待其执行完毕。可以通过在方法中依赖注入自己,并在异步方法中调用自己的方式来实现。具体步骤如下:
1. 在Service中定义一个异步方法,该异步方法调用要异步执行的方法。
```java
@Service
public class MyService {
@Autowired
MyService self; // 依赖注入自己
@Async
public void asyncMethod() {
self.doSomethingAsync();
}
public void doSomethingAsync() {
// 执行耗时操作
}
}
```
2. 在需要异步执行的方法中,调用异步方法。
```java
@Service
public class MyService {
@Autowired
MyService self; // 依赖注入自己
public void doSomething() {
// 执行同步操作
self.asyncMethod();
// 继续执行其他操作,无需等待异步方法执行完毕
}
@Async
public void asyncMethod() {
self.doSomethingAsync();
}
public void doSomethingAsync() {
// 执行耗时操作
}
}
```
需要注意的是,要在方法中依赖注入自己,需要使用@Autowired注解进行注入。这样可以确保在异步方法中调用的是代理对象,而不是实际的对象。这样才能使异步方法生效。