简体   繁体   中英

Spring scope request hashcode

In Spring, when the Scope of the bean is set to "request", for EACH request a new object will be generated. I want to test this but for every request I get the same hashcode value.

Question-

1. Should'nt the hash code value should be different since new object is generated.

Output for 4 http requests using Chrome and IE browser

emp hashcode == 172261326
emp hashcode == 172261326
emp hashcode == 172261326
emp hashcode == 172261326


@Controller
@RequestMapping("/welcome")
public class HelloController {
    @Autowired
    private Employee emp;

    public Employee getEmp() {
        return emp;
    }

    public void setEmp(Employee emp) {
        this.emp = emp;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        System.out.println("emp hashcode == " + emp.hashCode());
        emp.
        model.addAttribute("message", "Spring 3 MVC Hello World");
        return "hello";
}




@Component
@Scope(value="request")
public class Employee {
    private String fname;
    private int age;
    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Depending on the proxy mode you've chosen, Spring will provide an interceptor for the hashCode method. This will typically delegate the invocation to the advised object. You'd think that in this case the advised object would be the actual Employee object, but you'd be wrong. In reality, Spring provides a SimpleBeanTargetSource that knows how to retrieve your scoped bean.

There's only one SimpleBeanTargetSource object, so you're always getting the same hashCode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM