Reputation: 10413
I'm new to Spring Boot, I only like to use its dependency injection, not all its opinionated frameworks but some. I know there are other alternatives for this functionality, but I would like to learn more Spring.
I am trying to have a request scoped bean and populate it with regular dependency injection. My plan is to have some User object that I can populate hold some custom business details that is easy to access that makes code clean.
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
class MyBean {
@Autowired
lateinit var req: HttpServletRequest
@Autowired
lateinit var env: Environment
@PostConstruct
fun pc() {
println("I am constructed $this, $req, $env")
}
var a = 3
}
@RestController
class MyController {
@GetMapping("/api/xyz")
fun login(m: MyBean): Int {
println("new bean m")
return m.a
}
}
Every time I hit that endpoint, I see new objects are instantiated. However the inner dependencies are not autowired, they are always null. What am I doing wrong? Do I need to write a filter? But how would I know how to find all the endpoints that needs that bean to be initialized? If, I remove the request scope the variables are initialized.
Upvotes: 0
Views: 2589
Reputation: 391
RestControllers
are beans like Components
or Services
. So in all of these you should deal with injected dependencies the same way.
Coming to the example you were adding, beans should not be parameters of actual endpoint mappings. Asking for request specific information like headers, path variables or the payload body are candidates for endpoint mapping method arguments.
For a bean instance of your class MyBean
you should rather use a member variable injected directly or via the constructor of your MyController
(where constructor based injection is the recommended approach).
Don't be confused when injecting your MyBean
which is RequestScoped
in the constructor of MyController
: this is totally intended and works. Spring actually injects a proxy instance that will resolve to the request specific instance once your request is reaching the controller invocation.
Upvotes: 1