Thanks to Sotirios answer and comments exchange, I read more carefully section 5.5 and 9.6 of Spring reference documentation and found out the problem :
It is ok to have singleton @Service
(in my case the SPResolver
) referencing session or request scoped beans if you ensure :
- that you use some kind of AOP proxy mechanism so that when the @Service is created initially and the scoped beans does not exist, a proxy is created that will then reference correctly the scoped beans during program execution. That is what I was actually doing in my initial code thru the
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
line in the currentUser bean creation. - The scoped beans needs to be referenced in the
@Service
thru an interface and not directly with a Java Class, which I was not doing for theUser
class. Actually, the copy-paste example I took for the ConnectionRepository Bean was working as ConnectionRepository is an Interface.
Here is the working configuration class code :
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public CurrentUserContext currentUser() {
return new CurrentUserContextImpl();
}
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
String id = currentUser().getId();
if (id == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(id);
}
and the @Service declarations :
@Service
public class SPResolver {
public SPResolver() {
}
@Autowired
private CurrentUserContext currentUser;
@Autowired
private ConnectionRepository connectionRepository;