我编写了一个简单的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 RestTemplateBuilder : " + ctx.getBean("restTemplateBuilder"));
System.out.println(" Getting RestTemplate : " + ctx.getBean("restTemplate"));
}
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
@Bean
public CommandLineRunner runner() {
return args -> { SOP("hello"); }
}
}
观察:
题
为什么我会看到第2点和第3点中提到的结果?
在通过restTemplate()方法创建RestTemplate实例时,我尝试将参数名称更改为builder。有用。
这是有效的,因为默认弹簧自动装配的类型。所以它搜索类型为RestTemplateBuilder
的bean并找到它,因此没有错误。
在通过restTemplate()方法创建RestTemplate实例的同时,我尝试将方法的名称更改为随机方法,并且我得到一个例外,即“没有bean命名'restTemplate'可用”。
您获得异常不是因为您更改了方法名称,而是因为这一点
ctx.getBean("restTemplate")
因为默认情况下,@Bean
使用方法名称作为bean的名称。 (check this)。因此,随机方法返回的RestTemplate类型的bean的名称是随机方法的名称。因此,当您尝试获取名为restTemplate
的bean时,它会抛出异常。
但是如果您要使用RestTemplate类型的自动转发器,它仍然可以工作,因为默认情况下Spring会按类型自动装配,并且它知道一个类型为RestTemplate的bean(名称为随机方法名称)。