Spring作用域请求哈希码

时间:2014-11-30 03:56:18

标签: java spring spring-mvc

在Spring中,当bean的Scope设置为" request"时,对于EACH请求,将生成一个新对象。我想测试这个但是对于每个请求我得到相同的哈希码值。

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;
    }
}

1 个答案:

答案 0 :(得分:2)

根据您选择的代理模式,Spring将为hashCode方法提供拦截器。这通常会将调用委托给建议的对象。您认为在这种情况下,建议的对象将是实际的Employee对象,但您错了。实际上,Spring提供了一个知道如何检索作用​​域bean的SimpleBeanTargetSource

只有一个SimpleBeanTargetSource个对象,因此您始终可以获得相同的hashCode