Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring in spring 'byName' not working

Tags:

java

spring

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"

  1. Autowiring works correctly when the bean name is spelled correctly (StudentRepository). The setter method is setStudentRepository, so it calls that for setter injection.

  2. 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

  3. byType autowiring works everytime.

So why autowiring byName fails as mentioned in point 2.

like image 252
trim24 Avatar asked Oct 16 '22 10:10

trim24


1 Answers

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>
like image 92
Mykhailo Moskura Avatar answered Nov 15 '22 07:11

Mykhailo Moskura