了解实例变量名以及使用Spring@Bean注释创建它的方法
我已经编写了一个简单的Spring引导应用程序,稍后我将对其进行扩展以构建Spring REST客户机。我有一个工作代码;我试着改变了一些实例变量名和方法名,并进行了修改 代码:了解实例变量名以及使用Spring@Bean注释创建它的方法,spring,spring-boot,lambda,functional-interface,Spring,Spring Boot,Lambda,Functional Interface,我已经编写了一个简单的Spring引导应用程序,稍后我将对其进行扩展以构建Spring REST客户机。我有一个工作代码;我试着改变了一些实例变量名和方法名,并进行了修改 代码: @SpringBootApplication public class RestClientApplication { public static void main(String[] args) { SpringApplication.run(RestClientApplication.class, arg
@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"); }
}
}
观察结果:
restemplatebuilder
的bean,并找到它,因此没有错误
通过RestTemplate()方法创建RestTemplate实例时,
我尝试将方法的名称更改为随机名称,结果得到一个
例外情况是“没有名为“restemplate”的bean可用”
出现异常不是因为更改了方法名称,而是因为
ctx.getBean("restTemplate")
因为默认情况下,@Bean
使用方法名作为Bean的名称。(). 因此,随机方法返回的RestTemplate类型bean的名称就是随机方法的名称。因此,当您尝试获取名为restemplate
的bean时,它会抛出异常
但是,如果要自动连接RestTemplate类型的bean,它仍然可以工作,因为Spring默认情况下会自动连接类型,并且它知道RestTemplate类型的bean(名称为随机方法名)。非常感谢。我已经添加了与此代码相关的第4点。请回答这个问题。我对Spring核心、Spring上下文和DI有基本的了解。你能为我提供理解这些概念的推理参考资料吗?最好的方法是尝试不同的东西,找出答案,为什么它如此有效。不确定你是否能从阅读文档中学到一切。但是,如果你想阅读spring文档,那就从这里开始吧,我明白为什么#4如此有效。以“运行”的方式访问它是有效的。
@Bean(name=“restemplate”)
如果你像这样注释Bean,你可以在那里给出任何名称,但对象仍然是restemplate
@sara