[英]How to get spring-boot @Async to work with Java 8
我试图异步调用一个方法。 但不知怎的,它不起作用。 有人可以帮我解决这个问题吗?
我的主要切入点:
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
AsyncService asyncService = new AsyncService();
asyncService.asyncMethod();
asyncService.asyncMethod();
}
}
异步服务:
@Component
public class AsyncService {
@Async
public void asyncMethod(){
log.info("starting...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("ending...");
}
}
最后,在日志中我期待:
但这就是我得到的:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.2.RELEASE)
2019-02-13 17:52:41.548 INFO 85734 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on mntbden00122972 with PID 85734 (/Users/h3560/demo/target/classes started by h3560 in /Users/h3560/demo)
2019-02-13 17:52:41.550 INFO 85734 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-02-13 17:52:42.084 INFO 85734 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.76 seconds (JVM running for 1.329)
2019-02-13 17:52:42.086 INFO 85734 --- [ main] com.example.demo.services.AsyncService : starting...
2019-02-13 17:52:44.088 INFO 85734 --- [ main] com.example.demo.services.AsyncService : ending...
2019-02-13 17:52:44.089 INFO 85734 --- [ main] com.example.demo.services.AsyncService : starting...
2019-02-13 17:52:46.091 INFO 85734 --- [ main] com.example.demo.services.AsyncService : ending...
@Async
是spring的注释,它被应用于代理上的public
方法(这就是为什么它们需要公开)。 自我调用不起作用。
在您的示例中,您没有使用spring的依赖注入机制,因此不会创建任何代理。 要绕过它,你需要从中创建一个@Bean
(你用@Component
注释它已经完成)并在执行之前@Autowire
它:
@SpringBootApplication
@EnableAsync
public class DemoApplication {
@Autowired
AsyncService asyncService;
public someMethod() {
SpringApplication.run(DemoApplication.class, args);
asyncService.asyncMethod();
asyncService.asyncMethod();
}
}
有了这个弹簧,AOP可以将组件包装到代理中并异步执行该方法。
您遇到的问题是通过new
运算符手动实例化对象。 这不会给框架提供将对象包装在代理中的机会。 如果要使用Asynchronous方法,则必须使用Factory Methos,@ @Autowired
(或@Inject
)或使用XML配置的Spring DI。
如果你这样做,你可以制作System.out.println(obj.getClass())
,看看,注入DI的引擎盖下的bean不是你在那里使用的类,而是代理类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.