Thursday 12 August 2021

Spring Constructor Injection Part-1

Today we learn "Spring Constructor Injection"

  1. Open Eclipse and Create a New Core Java Project

  2. Then Add Spring Core Jar file to Project

  3. Project -> Properties - > Java Build Path -> Add External Jars

    Add Following Jar Files to Your Project


   4. Now create a package called mypack

   5. And Create init a Class named as DemoClass

   6.
    Class DemoClass

       {
          DemoClass()
         {
            System.out.println("Default Constructor");
         }
       }


7. Now Create a Configuration file called applicationContext.xml in this we defined how to beans are configured

applicationContext.xml 

a.) Firstly defined Spring namespace in top of the xml file like this

     <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

b.) Now we can access Spring bean related xml tag.

c.) Now we declare Bean Tag for Constructor injection, see

<bean name="name of the bean" class="fully qualified class name" scope="Singleton/Prototype"/>

Description:

name - Defined the desired name
class - in this we have to write fully qualified class name like this in our screnrio "mypack.DemoClass"

scope
- Scope are two types

            a.) Singleton: as name shows Singleton means we can create single instance of a bean only in application life.

           b.) Prototype: In this we can create multiple instance of a bean.

Note: Default scope of a bean is Prototype. 

Sometime we need single instance of a Object in whole application like SessionFactory in Hibernate Application or Connection object for Database related operation. According to our need we can choose either Singleton or Prototype.

Now apply this tag into XML configuration, After apply whole configuration file will look like this

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean name="Demo" class="mypack.DemoClass" scope="Prototype"/>

</beans>

8.) Now put this file to src folder of Project.

9.) Now we create a Main Class where we have to test how to get the bean.

10.)