@bean注解一个问题?

@Bean
    public RestTemplate initRestTemplate(){
        return new RestTemplate();
    }

这样注册了一个bean以后

为什么

@Autowired
    private RestTemplate restTemplate;

可以自动装配成功

我的问题是:

bean注册的id应该是方法名的小写驼峰
那在自动装配的时候应该用initRestTemplate才能找到的吧?

阅读 2.9k
2 个回答

@Autowired 是按类型匹配的。

Make sure that your target components (for example, MovieCatalog or CustomerPreferenceDao) are consistently declared by the type that you use for your @Autowired-annotated injection points. Otherwise, injection may fail due to a "no type match found" error at runtime.

https://docs.spring.io/spring...

Resource的话才会让你指定beanName,或者Autowired 搭配Qualifier指定beanName,单独用Autowired ,类型匹配

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题