Dependency Injection by Constructor ExampleWe can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is used for constructor injection. Here we are going to inject
Injecting primitive and string-based valuesLet's see the simple example to inject primitive and string-based values. We have created three files here:
It is a simple class containing two fields id and name. There are four constructors and one method in this class. applicationContext.xmlWe are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked. Test.javaThis class gets the bean from the applicationContext.xml file and calls the show method. Output:10 null Injecting string-based valuesIf you don't specify the type attribute in the constructor-arg element, by default string type constructor will be invoked. If you change the bean element as given above, string parameter constructor will be invoked and the output will be 0 10. Output:0 10 You may also pass the string literal as following: Output:0 Sonoo You may pass integer literal and string both as following Output:10 Sonoo download this example (developed using Myeclipse IDE) download this example (developed using Eclipse IDE) |