配置文件定义RestTemplate Bean与@Autowired注入共存时将使用哪个实例?
Great question—let’s unpack this step by step so you’re crystal clear on what’s happening.
First, let’s recap your setup to align on context:
- You’ve got an
ABCclass where you inject aRestTemplateusing@Autowired RestTemplate restTemplate; - You’ve defined a bean in your Spring XML config:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/> - You’re calling
restTemplate.postForObject(...)inABCand wondering which instance is being invoked.
Here’s the straightforward answer: You will be using the exact RestTemplate instance defined in your XML configuration file.
Why? Let’s break down Spring’s autowiring logic for this scenario:
- Spring loads your XML bean first: When the Spring container starts up, it parses your XML config, creates the
RestTemplateinstance with the idrestTemplate, and registers it in the container. - @Autowired matches by type first, then name:
- If there’s only one bean of type
RestTemplatein the container (which is your case), Spring will inject that bean regardless of the variable name. - Even if there were multiple
RestTemplatebeans, since your injected variable name (restTemplate) matches the bean id from your XML, Spring will prioritize that name match and inject the bean you defined in the XML.
- If there’s only one bean of type
- No ambiguity here: There’s no conflict or mystery—your XML-defined bean is the only
RestTemplatein the container, so it’s the one wired into yourABCclass.
As a quick side note: If you ever want to make this even more explicit (especially if you add other RestTemplate beans later), you can pair @Autowired with @Qualifier("restTemplate"), like this:
@Autowired @Qualifier("restTemplate") private RestTemplate restTemplate;
But in your current setup, this isn’t necessary—Spring handles the matching automatically thanks to the matching variable name and bean id.
So when you call restTemplate.postForObject(...), you’re definitely using the instance you configured in your Spring XML file.
内容的提问来源于stack exchange,提问作者pjj

