Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a session-scoped bean inside a controller

I'm experimenting with session-scoped beans in Spring 3. I have the following bean definition:

<bean id="userInfo" class="net.sandbox.sessionbeans.UserInfo" scope="session" />

Here is net.sandbox.controllers.RegistrationController, a controller class that needs access to this bean. I've taken out the imports for brevity's sake.

@Controller
@RequestMapping("/register")
public class RegistrationController {
    private UserInfo userInfo;   // This should reference the session-scoped bean

    @RequestMapping(method = RequestMethod.GET)
    public String showRegForm(Model model) {
        RegistrationForm regForm = new RegistrationForm();
        model.addAttribute("regform", regForm);
        return "regform";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String validateForm(@Valid RegistrationForm regForm, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "regform";
        }

        userInfo.setUserName(regForm.getFirstName());
        model.addAttribute("regform", regForm);
        return "regsuccess";
    }
}

Is there a way to automatically tie the session-scoped bean I defined to the member variable private UserInfo userInfo in RegistrationController?

like image 237
Pieter Avatar asked Jan 20 '23 19:01

Pieter


1 Answers

Yes - see section 3.4.5.4 of the Spring manual, "Scoped beans as dependencies".

Briefly, you can ask Spring to wrap your session-scoped bean in a singleton proxy, which looks up the correct session when you invoke a method on the scoped bean. This is called a "scoped proxy", and uses the <aop:scoped-proxy> config macro. You can then inject the reference as you would any other (e.g. <property>, or @Autowired). See the above link for details.

like image 106
skaffman Avatar answered Jan 28 '23 22:01

skaffman