Search code examples
javaspringspring-mvcautowiredsession-scope

How does Spring autowire session scoped beans?


I'm currently working with session objects. In service layer I'm autowiring session scoped bean. And I wonder how Spring is able to do this? And more interesting part, even if I use final keyword and use constructor injection, Spring is still able to autowire the object.

@Service
public class SomeServiceImpl implements SomeService {

    private final UserSessionDetails userSessionDetails;

    @Autowired
    public SomeServiceImpl(final UserSessionDetails userSessionDetails) {
        this.userSessionDetails = userSessionDetails;
    }
}

And my other question is; Is it good practice the using session objects in Service layer? Or am I free to use these objects in Controller and Service layers?


Solution

  • I wonder how Spring is able to do this?

    SomeServiceImpl is a singleton, so it should be assembled at startup. Assembling a bean means injecting all required dependencies to it. Although some candidates may have the scope different from the singleton scope, they still have to be provided. For such beans, Spring creates proxies. A proxy is basically a meaningless wrapper until some context comes.

    if I use final keyword and use constructor injection, Spring is still able to autowire the object.

    Spring supports constructor-based injection. It examines the signature and looks up candidates to inject; the modifiers of a field don't matter.

    Is it good practice the using session objects in Service layer? Or am I free to use these objects in Controller and Service layers?

    As long as the service is web-oriented and session-concerned, you are free to inject session-scoped beans to it.