Spring Autowire By Name
By AmarSivas | | Updated : 2021-05-09 | Viewed : 296 times

The current article shows how the
Table of Contents:
Spring Autowire By Name
Spring provides autowire for dependency injection of three types. one of the options is
Spring Autowire By Name Xml
We will see the
public class ASpringBean {
private String aSpringBeanName;
private BSpringBean bSpringBean;
}
public class BSpringBean {
private String bSpringBeanName;
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="aSpringBean" class="com.docsconsole.tutorials.byname.xml.ASpringBean" autowire="byName">
<property name="aSpringBeanName" value="aSpringBean"></property>
</bean>
<bean id="bSpringBean" class="com.docsconsole.tutorials.byname.xml.BSpringBean" >
<property name="bSpringBeanName" value="bSpringBean"></property>
</bean>
<bean id="bSpringBean1" class="com.docsconsole.tutorials.byname.xml.BSpringBean" >
<property name="bSpringBeanName" value="bSpringBean1"></property>
</bean>
</beans>
Notice beans1.xml. We have added property
Please below
public class SpringMainClient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans1.xml");
ASpringBean aSpringBean = context.getBean("aSpringBean", ASpringBean.class);
aSpringBean.displayASpringBean();
aSpringBean.getbSpringBean().displayBSpringBean();
}
}
Spring Autowire By Name Annotation
Now we will look at annotation on how to handle the spring bean autowire by name. Please notice the below-given examples.
@Getter
@Setter
public class ASpringBean {
private String aSpringBeanName;
@Autowired
private BSpringBean bSpringBean;
//other methods
}
@Getter
@Setter
public class BSpringBean {
private String bSpringBeanName;
//other methods
}
@Configuration
public class SpringAppConfig {
@Bean
public ASpringBean aSpringBean() {
return new ASpringBean("ASpringBean");
}
@Bean("bSpringBean")
public BSpringBean bSpringBean() {
return new BSpringBean("BSpringBean");
}
@Bean("bSpringBean1")
public BSpringBean bSpringBean1() {
return new BSpringBean("BSpringBean1");
}
}
Notice
To test the above SpringBeans you can use
public class SpringAppClient {
public static void main(String[] args) {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(SpringAppConfig.class);
context.registerShutdownHook();
//
ASpringBean aSpringBean = context.getBean(ASpringBean.class);
aSpringBean.displayASpringBean();
aSpringBean.getBSpringBean().displayBSpringBean();
}
}
For code repo, you can refer Spring-Autowiring-Example-App.