Spring Bean Autowiring by Autodetect

Autowiring by autodetect uses either of two modes i.e. constructor or byType modes. First it will try to look for valid constructor with arguments, If found the constructor mode is chosen. If there is no constructor defined in bean, or explicit default no-args constructor is present, the autowire byType mode is chosen.

Let's see the same example:

Required Files:

  • Address.java
  • Employee.java
  • spconfig.xml
  • Test.java

Address.java

package java8s;
public class Address
{
private String city;
private String state;
public String getCity()
{
return city;
}
public void setCity(String name)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state= state;
}
}

Employee.java

package java8s;
public class Employee
{
private String name;
private Address ad;
public Employee(Address ad)
{ //by Constructor
this.ad=ad;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void show()
{
System.out.println("Employee Name :"+ name);
System.out.println("Employee Address :"+ ad.getCity()+" "+ ad.getState());
}
}

spconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="id1" class="java8s.Employee" autowire="autodetect">
<property name="name" value="Trilochan Tarai" />
</bean>
<bean id="ad" class="java8s.Address">
<property name="city" value="Bhubaneswar" />
<property name="state" value="Odisha" />
</bean>
</beans>

Test.java

package java8s;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test
{
public static void main(String[] args)
{
Resource resource = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Object o = factory.getBean("id1");
Employee e = (Employee)o;
e.show();
}
}

Output
Employee Name:Trilochan Tarai
Employee Address:Bhubaneswar Odisha

Autodetect byType

If there is no constructor defined in bean, or explicit default no-args constructor is present, the autowire byType mode is chosen.

Example

package java8s;
public class DemoBean
{
private ExampleBean eb;
public ExampleBean getEb()
{
return eb;
}
public void setEb(ExampleBean eb)
{
System.out.println("autowiring by type");
this.eb = eb;
}
//...
}

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment