ByType is the default, but it is not unique. When a bean has more than one beanId, an error will be reported. In this case, we need to specify the beanId to implement the @autowire class. You’re going to use byName.
Let’s look at a project example
-
Define MailConfig class
public class MailConfig { private String subject; private String from; private String text; private String replyTo; private boolean html; ----- Copy the code
-
Register MailConfig with the Spring Bean through the configuration file and specify the Bean ID
<bean id="CommonRegBillMail" class="com.sunisco.par.service.listener.MailConfig"> <property name="from" value="[email protected] " /> <property name="replyTo" value="[email protected] " /> <property name="html" value="true" /> <property name="text"> <value><! [CDATA] Dear customer, #context# #url# #customer_code# #orgpwd# #footer# ]]></value> </property> </bean> <bean id="paymentVerificationImportEmailConfig" class="com.sunisco.par.service.listener.MailConfig"> <property name="from" value="[email protected] " /> <property name="replyTo" value="[email protected] " /> <property name="html" value="true" /> <property name="text"> <value><! [CDATA[dear customer #userCode# : #context#]] </value> </property> </bean>Copy the code
Here we see MailConfig class corresponding to the two beans id is a CommonRegBillMail, one is paymentVerificationImportEmailConfig
-
@autowired Inject dependencies
If you use this
@Autowired private MailConfig config; Copy the code
Will be an error, because the program does not know is to use CommonRegBillMail or paymentVerificationImportEmailConfig corresponding configuration, byName in this way
@Autowired @Qualifier("CommonRegBillMail") private MailConfig config; Copy the code
The byName approach uses the @qualifier annotation, which implements dependency lookup based on parameters. There will be no errors.
-
Depend on the use
MimeMessageHelper helper = new MimeMessageHelper(message, true, Charsets.UTF_8.name()); helper.setFrom(config.getFrom()); ------- Copy the code
The above is the flow and scenario of @Autowired via ByName and ByType injection. If you want to understand the underlying implementation principle, you are recommended to see the source code implementation of the two injection methods in “Spring Source In-depth Analysis” page 117.