@bean注解一个问题?

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

这样注册了一个bean以后

为什么

@Autowired
    private RestTemplate restTemplate;

可以自动装配成功

我的问题是:

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

阅读 3k
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 ,类型匹配

推荐问题