mnesimi
mnesimi

Reputation: 65

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?

Upvotes: 3

Views: 2065

Answers (2)

Andrew
Andrew

Reputation: 49656

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.

Upvotes: 2

Dargenn
Dargenn

Reputation: 402

You are autowiring by constructor, so the usage of word final does not change anything in this case. By annotating UserSessionDetails as session scoped bean, and injecting it into SomeServiceImpl spring generates a proxy. Any call from your service, is being delegated into UserSessionDetails bean.

Upvotes: 0

Related Questions