The exception in question is due to the mix of annotations before the bean. These beans are managed by Spring in my case. Therefore, except for the @Controller
annotation the rest of the two annotations are simply ignored and ultimately, the bean has only one annotation which is @Controller
.
The problem is that the Spring bean registration annotation @Controller
defaults to the application scope (regarding Spring, it is actually singleton). Therefore, the bean in question is loaded on application start up (when no request is made and no session is created) and the secured service method sharableService.getCountryList();
is invoked as soon as the dependency injections are applied and the constructor of the bean is called where SecurityContext
is not available as obvious. Hence, the exception.
The bean should now be modified as follows.
import java.io.Serializable;
import admin.dao.service.StateService;
import admin.dao.service.SharableService;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
@Controller
@Scope("view") //or other scope as needed.
public final class StateManagedBean extends LazyDataModel<StateTable> implements Serializable
{
@Autowired
private final transient StateService stateService=null;
@Autowired
private final transient SharableService sharableService=null;
private List<Country>countries;
public StateManagedBean(){}
@PostConstruct
public void init()
{
countries=sharableService.getCountryList(); //Works fine now.
}
//The rest of the managed bean.
}
The view scope has been customized of course, see also, since Spring doesn't have such a scope as view.
I realized this after a long time when BalusC commented on many of my posts. (Nothing to abuse but some articles/blogs misled me :)).