0

How can we know if spring framework is using constructor based dependency injection or setter method based dependency injection, when both the constructor and setter method is defined?

for example.. I have two java classes as follows.. TextEditor.java

public class TextEditor {
    private SpellChecker spellChecker;

    TextEditor(SpellChecker spellChecker){

       this.spellChecker = spellChecker;
    }


    public void setSpellChecker(SpellChecker spellChecker) {

      this.spellChecker = spellChecker;
    }

   // a getter method to return spellChecker
    public SpellChecker getSpellChecker() {
      return spellChecker;
    }

    public void spellCheck() {
      spellChecker.checkSpelling();
    }
}

and SpellChecker.java

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

in configuration file, pom.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <property name="spellChecker">
         <bean id="spellChecker" class="SpellChecker"/>
       </property>
   </bean>

</beans>

now, how can we know that spring has added dependency using Constructor or using Setter method?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Prashant
  • 31
  • 7

2 Answers2

2

When using a <property>, spring injects dependencies via setter.

If you want to inject it via constructor, you use <constructor-arg>.

Also see: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators

Carl Walsh
  • 6,100
  • 2
  • 46
  • 50
Seb
  • 1,721
  • 1
  • 17
  • 30
0

It is all about developer choice how does he/she configure spring to inject dependency.

Since everyone could write big wall of text about how Dependency Injection works you should see/read this:

http://www.journaldev.com/2410/spring-dependency-injection-example-with-annotations-and-xml-configuration

Paweł Głowacz
  • 2,926
  • 3
  • 18
  • 25