Два разных хеш-кода для объекта, созданного с помощью Spring Boot в одном контексте - PullRequest
0 голосов
/ 30 августа 2018

Я написал простое Spring Boot Application, которое позже расширил бы для создания 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);
    };
}

}

Наблюдение

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

Вопрос Я предположил, что хэш-коды одинаковы. Это ожидаемое поведение? Да, как?

1 Ответ

0 голосов
/ 30 августа 2018

Вы создаете два различных контекста 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"));
}

Итак, результат ожидается.

...