1

XML

<bean name="helloWorld" class="com.company.HelloWorld">
    <property name="msg" value="messaging"/>
</bean>

JAVA

package com.company;

// ...

public class HelloWorld {
    private String msg;
    public void setMsg(String msg) { this.msg = msg; }
}

As shown above, property "msg" is injected into "this.msg" by "setMsg" method, which I understand as "Property Injection". As far as I'm concerned, Spring's DI was promoted to decouple classes, but the above codes just inject properties. And I wonder whether property injection is based on DI in Spring. Hope someone could help me.

H. Guo
  • 63
  • 1
  • 8

3 Answers3

0

Injection means that the required dependencies (in your case: a simple String) are set from outside (this could be done manually or as in your case by a DI container - spring). So your class does not have to know where the value of "msg" is configured / retrieved, but it knows that (upon creation) it receives the correct value.

To answer your question: yes, property injection is a kind of dependency injection. The other possibility (that is usually preferred) is the constructor-injection, where your class has to declare all it's dependencies within the constructor. The DI framework (spring) then injects the dependencies during object construction...

Andreas Aumayr
  • 1,006
  • 1
  • 11
  • 17
0

As far as I'm concerned, Spring's DI was promoted to decouple classes, but the above codes just inject properties. And I wonder whether property injection is based on DI in Spring.

Assume that your HelloWorld class is dependent upon some other interface called LanguageHelper, then you can inject the implementation of LanguageHelper dynamically at run time (Spring container creates/manages the objects for these classes, if found on the classpath), just by specifying the implementation class name in XML as shown below (or you can use Annotations):

<bean id = "helloWorld" class = "com.company.HelloWorld">
      <property name = "languageHelper" ref = "languageHelper"/>
</bean>

<bean id = "languageHelper" class = "com.company.LanguageHelperImpl"></bean>

But, in your case, it is a simple String value you want to inject to your bean dynamically at runtime (rather than hard coding in your class directly). So, it is an injection for which there are no additional dependencies to be evaluated, rather just set the values using the setter methods provided.

So, it is all about how we can loose couple the class (could be simple values or other class implementation) for the future changes, rather than directly hard coding inside it.

Vasu
  • 21,832
  • 11
  • 51
  • 67
0

Martin Flowers "Inversion of Control Containers and the Dependency Injection pattern" should be a great read about Inversion of Control design pattern.

As per Martin Flower's post, injection can happen using constructor, setter injection and interface. Spring do support all 3 injection pattern.

Naveen Kumar
  • 893
  • 11
  • 19