Spring Autowire By Type
By AmarSivas | | Updated : 2021-05-09 | Viewed : 253 times

The current tutorial will exposure for
Table of Contents:
Spring Autowire By Type
Spring supports
Spring Autowire By Type Xml
Let\'s code for spring autowire by type. So please look at these below-given code blocks for the same.
public class ASpringBean {
private String aSpringBeanName;
private BSpringBean bSpringBean;
//other methods
}
public class BSpringBean {
private String bSpringBeanName;
//other methods
}
Now we will configure these two beans in xml. Notice below given xml snippet.
<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.bytype.xml.ASpringBean" autowire="byType">
<property name="aSpringBeanName" value="aSpringBean"></property>
</bean>
<bean id="bSpringBean" class="com.docsconsole.tutorials.bytype.xml.BSpringBean" >
<property name="bSpringBeanName" value="bSpringBean"></property>
</bean>
</beans>
When you create the
public class SpringMainClient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
ASpringBean aSpringBean = context.getBean("aSpringBean", ASpringBean.class);
aSpringBean.displayASpringBean();
aSpringBean.getbSpringBean().displayBSpringBean();
}
}
Use this Client for testing the spring autowire by type.
Spring Autowire By Type Annotation
Now we will try the
@Getter
@Setter
public class ASpringBean {
private String aSpringBeanName;
@Autowired
private BSpringBean bSpringBean;
//other methods
}
@Getter
@Setter
public class BSpringBean {
private String bSpringBeanName;
//other methods
}
We will set up config for both beans as given below configuration class.
@Configuration
public class SpringAppConfig {
@Bean
public ASpringBean aSpringBean() {
return new ASpringBean("ASpringBean");
}
@Bean
public BSpringBean bSpringBean() {
return new BSpringBean("BSpringBean");
}
}
In the time of instantiating
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();
}
}
Please use the client class for testing the