91-9990449935 0120-4256464 |
Autowiring in SpringAutowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection. Autowiring can't be used to inject primitive and string values. It works with reference only. Advantage of AutowiringIt requires the less code because we don't need to write the code to inject the dependency explicitly. Disadvantage of AutowiringNo control of programmer. It can't be used for primitive and string values. Autowiring ModesThere are many autowiring modes:
Example of AutowiringLet's see the simple code to use autowiring in spring. You need to use autowire attribute of bean element to apply the autowire modes. Let's see the full example of autowiring in spring. To create this example, we have created 4 files.
This class contains a constructor and method only. A.javaThis class contains reference of B class and constructor and method. applicationContext.xml Test.javaThis class gets the bean from the applicationContext.xml file and calls the display method. Output: b is created a is created hello a hello b 1) byName autowiring modeIn case of byName autowiring mode, bean id and reference name must be same. It internally uses setter injection. But, if you change the name of bean, it will not inject the dependency. Let's see the code where we are changing the name of the bean from b to b1. 2) byType autowiring modeIn case of byType autowiring mode, bean id and reference name may be different. But there must be only one bean of a type. It internally uses setter injection. In this case, it works fine because you have created an instance of B type. It doesn't matter that you have different bean name than reference name. But, if you have multiple bean of one type, it will not work and throw exception. Let's see the code where are many bean of type B. In such case, it will throw exception. 3) constructor autowiring modeIn case of constructor autowiring mode, spring container injects the dependency by highest parameterized constructor. If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection will be performed by calling the two-arg constructor. 4) no autowiring modeIn case of no autowiring mode, spring container doesn't inject the dependency by autowiring.
Next TopicDependency Injection with Factory Method
|