我已经编写了一个简单的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
问题 我认为哈希码是相同的。这是预期的行为吗?是的,如何?
答案 0 :(得分: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"));
}
所以预期的结果。