Reputation: 779
I have a @RestController which has an injected @Service bean. I am having trouble understanding the lifespan of the Controller and its Service. Is it on a per-request basis? Or is it longer than that? I am new to Spring and how beans are managed.
@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)
}
...
}
The reason I ask is because we are instantiating a sql connection within the service and I am curious if I can memoize and reuse the connection or if I will have one instance per request that needs to be closed immediately.
Spring Boot 1.5.2
Upvotes: 3
Views: 1470
Reputation: 62555
@RestController
is a shorthand for @Controller
and @ResponseBody
. It respect the MVC principles.
@Service
is a specialisation of @Component
and respect the Business Service Facade pattern (in the Core J2EE patterns sense).
It follows that, the lifespan of these annotations is the lifespan of the whole application.
You can also read Spring @Component, @Repository, @Service and @Controller Annotations for more information.
Upvotes: 2