Two different hash codes for an object created through Spring Boot in the same context

╄→гoц情女王★ 提交于 2019-12-08 03:30:54

问题


I have written a simple Spring Boot Application, which I would later extend to build a Spring REST client. I have a working code; I am playing around to understand the concepts better. The code is as follows.

@SpringBootApplication
public class RestClientApplication {

public static void main(String[] args) {
    SpringApplication.run(RestClientApplication.class, args);

    try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
            RestClientApplication.class)) {
        System.out.println(" Getting RestTemplate : " + ctx.getBean("restTemplate"));
    }
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.build();
}

@Bean
public CommandLineRunner run(RestTemplate template) {
    return args -> {
        System.out.println("Rest Template instance from CLR is : " + template);
    };
}

}

Observation

Rest Template instance from CLR is : org.springframework.web.client.RestTemplate@1e53135d
Getting RestTemplate : org.springframework.web.client.RestTemplate@5aa6202e

Question I presumed the hashcodes to be the same. Is this the expected behaviour? Is yes, how?


回答1:


You create two distinct Spring contexts :

// first context
SpringApplication.run(RestClientApplication.class, args);

// second context
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
        RestClientApplication.class)) {
    System.out.println(" Getting RestTemplate : " + ctx.getBean("restTemplate"));
}

So the result is expected.



来源:https://stackoverflow.com/questions/52098453/two-different-hash-codes-for-an-object-created-through-spring-boot-in-the-same-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!