I'm new to Spring. Currently starting with xml configuration, so please don't say to use Annotations. I was reading about autowiring 'byName', and i'm confused on how it works.
My Config file -
<bean name="StudentRepositor"
class="com.sample.Repository.StudentRepositoryHibernate"/>
<bean name="StudentService"
class="com.sample.Service.StudentServiceQuery" autowire="byName">
<!--<property name="StudentRepositor" ref="StudentRepositor" />-->
</bean>
StudentServiceQuery class-
public class StudentServiceQuery implements StudentService {
private StudentRepository studentRepositor;
public void displayList() {
List<Student> studentList = studentRepositor.returnList();
System.out.println(studentList.get(0).toString());
}
public void setStudentRepositor(StudentRepository studentRepositor) {
System.out.println("Dependency Injection - Setter");
this.studentRepositor = studentRepositor;
}
}
Name of the class for bean name "StudentRepositor" is "StudentRepository"
Autowiring works correctly when the bean name is spelled correctly (StudentRepository). The setter method is setStudentRepository, so it calls that for setter injection.
When i spell the bean name incorrectly( StudentRepositor ), then if i use property to refer the class, it works. But it fails when i do 'autowiring byName'. The setter method is setStudentRepositor
byType autowiring works everytime.
So why autowiring byName fails as mentioned in point 2.
When you are declaring a bean :
<bean name="StudentRepositor"
class="com.sample.Repository.StudentRepositoryHibernate"/>
The name of bean should not be similar with the name of class it could be any
When you are injecting those declared bean into another one :
<bean name="StudentService"
class="com.sample.Service.StudentServiceQuery" autowire="byName">
<property name="StudentRepositor" ref="StudentRepositor" />
</bean>
The ref must be the same you declared bean name section so if the name is StudentRepositor the ref should be the same (StudentRepositor)
For property name when you are injecting it should be the same property name in the class
So if you have such class :
public class A{
private StudentRepositor b;
}
The name of property in your xml file should be 'b':
<bean name="StudentService"
class="com.sample.Service.StudentServiceQuery" autowire="byName">
<property name="b" ref="StudentRepositor" />
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With