在同一上下文中通过Spring Boot创建的对象的两个不同哈希码

Sar*_*ara 1 spring applicationcontext spring-boot

我编写了一个简单的Spring Boot应用程序,稍后我将扩展它以构建Spring REST客户端.我有一个工作代码; 我正在玩弄更好地理解这些概念.代码如下.

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

}
Run Code Online (Sandbox Code Playgroud)

意见

Rest Template instance from CLR is : org.springframework.web.client.RestTemplate@1e53135d
Getting RestTemplate : org.springframework.web.client.RestTemplate@5aa6202e
Run Code Online (Sandbox Code Playgroud)

问题 我假设哈希码是相同的.这是预期的行为吗?是的,怎么样?

dav*_*xxx 5

您创建两个不同的Spring上下文:

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

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

所以结果是预期的.