Spring Boot @RestController 和注入的@Service 的生命周期是多少?

What is the lifespan of a Spring Boot @RestController and an injected @Service?

我有一个@RestController,它有一个注入的@Service bean。我无法理解控制器及其服务的生命周期。它是基于每个请求的吗?或者比那更长?我不熟悉 Spring 以及 beans 的管理方式。

@RestController
class AppController {

    private final AppService appService

    AppController(AppService appService) {
        this.appService = appService
    }
    ...
}

@Service
class AppService {

    private final DataSource dataSource

    AppService(DataSource dataSource) {
        this.dataSource = dataSource
    }

    private Sql getSql() {
        new Sql(dataSource.connection)
    }
    ...
}

我问的原因是因为我们正在服务中实例化一个 sql 连接,我很好奇我是否可以记住并重用该连接,或者我是否每个请求都有一个需要关闭的实例立即。

Spring 引导 1.5.2

@RestController@Controller@ResponseBody 的 shorthand。它尊重 MVC principles.

@Service@Component 的特化,并且尊重 Business Service Facade pattern(在核心 J2EE 模式意义上)。

由此可见,这些注解的生命周期就是整个应用的生命周期。

您还可以阅读 Spring @Component, @Repository, @Service and @Controller Annotations 了解更多信息。