91-9990449935 0120-4256464 |
Dependency Injection with Factory Method in SpringSpring framework provides facility to inject bean using factory method. To do so, we can use two attributes of bean element.
A method that returns instance of a class is called factory method. Factory Method TypesThere can be three types of factory method: 1) A static factory method that returns instance of its own class. It is used in singleton design pattern. 2) A static factory method that returns instance of another class. It is used instance is not known and decided at runtime. 3) A non-static factory method that returns instance of another class. It is used instance is not known and decided at runtime. Type 1Let's see the simple code to inject the dependency by static factory method. Let's see the full example to inject dependency using factory method in spring. To create this example, we have created 3 files.
This class is a singleton class. applicationContext.xml Test.javaThis class gets the bean from the applicationContext.xml file and calls the msg method. Output: private constructor factory method hello user Type 2Let's see the simple code to inject the dependency by static factory method that returns the instance of another class. To create this example, we have created 6 files.
This class gets the bean from the applicationContext.xml file and calls the print() method. Output: hello a Type 3Let's see the example to inject the dependency by non-static factory method that returns the instance of another class. To create this example, we have created 6 files.
All files are same as previous, you need to change only 2 files: PrintableFactory and applicationContext.xml. PrintableFactory.java applicationContext.xmlOutput: hello a
Next TopicSpring AOP Tutorial
|