Spring Setter Dependency Injection(No Arg Factory Method)

In Setter based DI(Dependency Injection), Objects define their dependencies via properties (<property> tag) and Container invoke setter methods to set these properties in object instance after invoking a no-argument constructor or no-argument static factory method to instantiate the bean.

To make setter injection work No-Argument Constructor(Default/Explicit) or No-Argument Static factory method is required. In this topic we will discuss about the DI using no arg static factory method. Click here to learn Spring DI using No Arg Constructor.

Arg Static Factory Method can also be used but in that case argument will be passed as “constructor-arg” elements to specify arguments to the factory.

 

Bean Class(To  Dependency Inject)

 Here we have overriden “toString” method to view meaningfull output for the programmme.

Spring Configuration File

Here we have mentioned the init factory(factory-method attribute) method that needs to be used to create Object.
In Configuration file we use “class” attribute to provide the fully qualified name of the bean’s class.
And “name” attribute is used to create aliases(address1 & address2)

Execute Application(Dependency Inject Bean)

Output of the above programme

 Important Points related to Factory Method:

  • Return type should be Non Void.
  • Factory Method needs to be static.
  • Autowiring does not apply to factory methods.
  • Factory method can have any number of arguments.(Not Applicable to this situation)
  • If Factory method takes arguments it should be specified by constructor-arg elements.

 

Environment Used

Tool : Eclipse Indigo

Java : JDK 1.6

Spring : 3.1.1

Jars Required :

  • org.springframework.core-3.1.1.RELEASE.jar
  • org.springframework.context-3.1.1.RELEASE.jar
  • org.springframework.asm-3.1.1.RELEASE.jar
  • org.springframework.beans-3.1.1.RELEASE.jar
  • org.springframework.expression-3.1.1.RELEASE.jar
  • commong-logging-1.1.1.jar

Leave A Comment

Your email address will not be published. Required fields are marked *