3

I created a simple session scoped bean in Spring 3.1. It is supposed to give me easy access to the Company of the currently logged in user.

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionData {

    private Company company;

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }
}

I am populating this bean with a Company in my custom authentication provider's authenticate() method.

@Component(value = "authenticationProvider")
public class ProduxAuthenticationProvider implements AuthenticationProvider {

    private SessionData sessionData;
    private CompanyService companyService;

    @Autowired
    public ProduxAuthenticationProvider(SessionData sessionData, CompanyService companyService) {
        this.sessionData = sessionData;
        this.companyService = companyService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // Authentication logic (token creation) removed for readability....

        Company company = companyService.findByUserProfile(profile);

        // Set company on session bean
        sessionData.setCompany(company);

        return token;
    }
}

And then I am trying to access the company field in ManagementHomeController, which runs after authentication has finished successfully.

@Controller
@RequestMapping(value = "/manage/home")
public class ManagementHomeController {

    private CourseService userService;
    private CompanyService companyService;
    private SessionData sessionData;

    @Autowired
    public ManagementHomeController(CourseService userService, CompanyService companyService, SessionData sessionData) {
        this.userService = userService;
        this.companyService = companyService;
        this.sessionData = sessionData;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String get(Model model) {
        model.addAttribute("mainContent", "content/managementHome");

        // sessionData.company is null here! Object id is same as in ProduxAuthenticationProvider

        return "main";
    }
}

Somehow in the ManagementHomeController the company field of SessionData is null, but it is the same object. I can see that because sessionData's object ID is the same in ProduxAuthenticationProvider and ManagementHomeController.

Any idea why SessionData is losing its company along the way?

4

1 に答える 1

2

Not completely sure if this will work, but from I understand since you are injecting a session scoped bean into a filter which is called prior to the Spring Dispatcher servlet being called certain request attributes required for the scoped proxy to work correctly may not have been set correctly.

The fix will be to move this logic to either a Spring Interceptor or to register a RequestContextListener in your web.xml

于 2012-11-11T00:05:44.143 に答える