问题
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