Spring

Content

  • Spring Core
  • Spring Data Integration
  • Spring WEB
  • Spring Other important module 

What is Spring ?
Spring is a database injection framework to make java application loosely coupled.

Spring framework makes the easy developed of JavaEE application.

It was developed by Road Johnson in 2003.

What is Dependency injection ?
Its design pattern.
Inversion of control : In dependency is capability to create object at runtime.

Spring Module : 

  • Spring Core Module
    • Core
    • beans
    • Context
    • spEl
    • AOP
    • Aspect
    • Instrumentation
    • Messaging 
  • Data Access/Integration
    • JDBC
    • ORM
    • JMS
    • OXM
  • Web
    • Web
    • Servlet
    • Portlet
    • WebSocket
  • Test

Spring IOC containter - It is predefined program those managed Object life Cycle
Help of this object ready to use object our application. we don't need to create object.


 ApplicationContext -:

  • ClasspathXMLApplicationContext
  • AnnotationConfiApplicationContext
  • FileSystemXMLApplicationContext

Property Injection using P schema and using value as attribute

Primitive Type:

By using value tag
<bean class="com.spring.student" name="student1">
      <property name="studentId">
         <value>2222</value>
       </property>
      <property name="studentName">
         <value>XYX</value>
      </property>
      <property name="studentAdderss">
         <value>India</value>
      </property>
</bean>

By Using Attribute
<bean class="com.spring.student" name="student1">
      <property name="studentId" value="222"/>
      <property name="studentName" value="ABC"/>
     <property name="studentAdderss" value="India"/>
</bean>

By Using P Schema
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/spring-context.xsd" >
    
    <!-- this is our beans -->
    <bean
       class="com.springcore.Student"
       name="student1"
       p:studentId="234" 
       p:studentName="ZVK"
       p:studentAddress="Satkur"/>
    

    <bean
       class="com.springcore.Student"
       name="student2"
       p:studentId="234" 
       p:studentName="ZVK"
       p:studentAddress="Satkur"/>

</beans>

By Using Collection Types:
 

List
<bean>
    <property name="">
       <list>
           <value>10<value>
           <value>20<value>
           <value>30<value>
           <null/>
       </list>
    </property>
</bean>

Set
<bean>
    <property name="">
       <set>
           <value>10<value>
           <value>20<value>
           <value>30<value>
       </set>
    </property>
</bean>

Map

Map
<bean>
    <property name="">
       <map>
           < entry key="java" value="10" />
           < entry key="python" value="30" />
           < entry key="C" value="40" />
       </map>
    </property>
</bean>

Properties
<bean>
    <property name="">
       <props>
          <prop key="name">Viaksh</prop>
            <prop key="channelName"> Code with Karma</prop>
         </props> 
    </property>
</bean>

Reference Injection 

A
Reference Inject:

<bean>
    <property name="">
        <ref bean="b">
    <property>
</bean>

Constructor Injection

As a Value : 

<constrcutor-args>
    <value>v</value>
<constructor-args> 

As a Tag

<constructor-args>
     <ref bean=" ">
<constructor-args>

If any class having 2 or more constructor then in this case we need to specify "type" 

ex:

<constrcutor-args value="India"/>
<constructor-args value="13" type="int"> 

File : Addition.java
public class Addition {
    private int a;
    private int b;
    public Addition(int a, int b) {
        this.a = a;
        this.b = b;
        System.out.println("Constrcutor int , int");
    }
    public Addition(double a, double b) {
        this.a = (int)a;
        this.b = (int)b;
        System.out.println("Constrcutor double double" );
    }
    public void doAdd() {
        System.out.println("Sum is "+( a + b));
    }
}

File ciconfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/spring-context.xsd">

    <bean class="com.springcore.ci.Addition"  name="add" >
         <constructor-arg value="10" type="double"/>
         <constructor-arg value="20" type="double"/>
    </bean>

</beans>

Life Cycle Methods
Spring provide two important methods to every bean

public void init() - Initialization code Loading config Connectiong db, Webservice etc

public void destory() -
Clean up code

We can change the name of there methods But signature must be same.

Life Cycle

start 

Spring Bean(Give class name to IOC ) 

Configruation Xml File (Give) 

init()  (call Init method)
    then we read and use the bean


destroy() : clean the code 

end

Configuration Technique

  • Xml
  • Spring Interface
  • Annotation

Implemetation LifeCycle method of Spring bean using XML

File : config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/spring-context.xsd" >
    
    <bean class="com.springcore.lifycyle.Samosa" name="s1" init-method="init" destroy-method="destroy">
          <property name="price" value="10"/>
    </bean> 
</beans>
File : Samosa.java
package com.springcore.lifycyle;

public class Samosa {
    private double price;

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        System.out.println("setting price");
        this.price = price;
    }

    public Samosa(double price) {
        super();
        this.price = price;
    }

    public Samosa() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Samosa [price=" + price + "]";
    }
    public void init() {
        System.out.println("Inside init");
    }
    public void destroy() {
        System.out.println("Inside destroy");
    }
}
File Test.java
package com.springcore.lifycyle;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    public static void main(String[] args) {
        AbstractApplicationContext  context = new ClassPathXmlApplicationContext("com/springcore/lifycyle/config.xml");
        Samosa s = (Samosa)context.getBean("s1");
       
        System.out.println(s);
        //registering shutdown hook
        context.registerShutdownHook();  
    }
}
Output : 

setting price
Inside init
Samosa [price=10.0]
Inside destroy

Implementing Bean LifeCycle using Interfaces InitializingBean DisposableBean


implementing
InitializingBean

File : Pepsi.java

package com.springcore.lifycyle;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Pepsi implements InitializingBean, DisposableBean {
    public double price;

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Pepsi(double price) {
        super();
        this.price = price;
    }

    public Pepsi() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Pepsi [price=" + price + "]";
    }

    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        //init()
        System.out.println("taking pepsi");
       
    }

    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Going to put botel back to shop : destroy");
       
    }

}
File : config.xml

<bean class="com.springcore.lifycyle.Pepsi" name="p1">
        <property name="price" value="5"></property>

</bean>

Using Annotations
Implementing Bean LifeCycle Annotations
@PostConstruct (init)
@PreDestroy

Autowiring in Spring:
Feature of spring Framework in which spring containter inject the dependencies automatically.

Autowiring can't be used  to inject primitive and string values. It works with reference only 

Autowiring 

Autowiring Advantage

  • automatic
  • less code

Autowiring Disadvatage

  • No control of programmer
  • It can't be used for primitive and string value 

Configuration

  •  XML
    Autowring mod 
    • no
    • byName
    • byType
    • constructor
    • autodetect (It is deorecated since Spring 3.)

          <bean class="com.springcore.auto.wire.Address" name="address">
               <property name="street" value="RB"/>
               <property name="city" value="Khargone" />
          </bean>
          
          <!-- <bean class="com.springcore.auto.wire.Emp" name="emp" autowire="byName" />      -->
          <!-- <bean class="com.springcore.auto.wire.Emp" name="emp" autowire="byType" />     -->
          <!-- <bean class="com.springcore.auto.wire.Emp" name="emp" autowire="constructor" />   -->
          <bean class="com.springcore.auto.wire.Emp" name="emp" autowire="byType" /> 


  • Annotation 
    • @Autowire
      File : config.xml
       <context:annotation-config></context:annotation-config>

          <bean class="com.springcore.auto.wire.annotation.Address" name="address">
               <property name="street" value="RB"/>
               <property name="city" value="Khargone" />
          </bean>

          <bean class="com.springcore.auto.wire.annotation.Emp" name="emp1"   /> 
      File : Emp.java
      package com.springcore.auto.wire.annotation;

      import org.springframework.beans.factory.annotation.Autowired;

      public class Emp {
          @Autowired //propertyAnnotation
          private Address address;

          public Address getAddress() {
              return address;
          }
          @Autowired //setterInjection
          public void setAddress(Address address) {
              this.address = address;
          }

          public Emp(Address address) {
              this.address = address;
          }
          @Autowired //ConstructorInjection
          public Emp() {
              super();
              // TODO Auto-generated constructor stub
              System.out.println("Inside constructor");
          }

          @Override
          public String toString() {
              return "Emp [address=" + address + "]";
          }
          
      }
      File : Address.java
      package com.springcore.auto.wire.annotation;

      public class Address {
          private String street;
          private String city;
          public String getStreet() {
              return street;
          }
          public void setStreet(String street) {
              this.street = street;
          }
          public String getCity() {
              return city;
          }
          public void setCity(String city) {
              this.city = city;
          }
          @Override
          public String toString() {
              return "Address [street=" + street + ", city=" + city + "]";
          }
      }
      File : Test.java
      package com.springcore.auto.wire.annotation;

      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;

      public class Test {
          public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("com/springcore/auto/wire/annotation/config.xml");
            Emp emp = context.getBean("emp1", Emp.class);
            System.out.println(emp);
          }
      }

Spring Standalone collection:
File alone_config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/spring-context.xsd
    http://www.springframework.org/schema/util
 http://www.springframework.org/schema/util/spring-util.xsd ">


    <!-- standalone list -->
    <util:list list-class="java.util.LinkedList" id="mylist">
        <value>Prem</value>
        <value>Piyush</value>
        <value>vikash</value>
    </util:list>

    <bean class="com.springcore.standalone.collection.Person"
        name="person1">
        <property name="friends" ref="mylist"/>
        <!-- <property name="friends">
            <ref bean="mylist" />
        </property> -->
    </bean>

</beans>

Stereotype Annotations

 
<context:component-scan base-package="com.springcore.streotype" />

Bean Scope:

Configure bean scope :

  • Using xml 
    • <bean class="" name=" " scope=" " />

  • Using Annotation
    @Component
    @Scope(" ")
    Class Student{
      ................
    }
  • Singleton (By Default)
  • prototype (Every-time new Object provide)
  • request  (Associate Web Application)
  • session
  • globalsession (Port rated Applications)

Spring Expression Language (SpEL) :
Supports Parsing and executing expression with the help of @Value Annotation.
Example : 

@Component
@Scope("prototype")
public class Student {
 
    @Value("Vikash")
    private String studentname;
    
    @Value("Delhi")
    private String city;
    @Value("#{temp}")   //Inject collection using Annotation
    private List<String> address;
    
    public List<String> getAddress() {
        return address;
    }
    public void setAddress(List<String> address) {
        this.address = address;
    }
    public String getStudentname() {
        return studentname;
    }
    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Student [studentname=" + studentname + ", city=" + city + ", address=" + address + "]";
    } 
}


Expression (
classes, Varibles, Methods , Constructor, and Object)
Symbol (
char,numaric, operator, keywords, and special symbols which return a value)

Syntext: @Value("#{Expression/symbol}")
example:
@Value("#{11+12}")
@Value("#{8>6?88:55}")
We can also call static methods, Object Methods, Varibles

How to invoke static methods and varibles?
Syntax : 

T(class).method(param)
T(class).varible

How to create Object
@Value("new java.lang.String('Karma')")

Removing Complete XML for scanning Configuration :

How to configure javaclass withouth using xml file
File : Student.java
package com.springcore.javaconfig;


import org.springframework.stereotype.Component;


@Component("student")
public class Student {
    public void study() {
        System.out.println("Runnintg");
    }
}

File : Demo.java

package com.springcore.javaconfig;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Demo {
    public static void main(String[] args) {
       
        ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        
        Student std = (Student)context.getBean("student", Student.class);
        System.out.println(std);
        std.study();    
    }
}

Now we need to one extra class called javaconfig.java
FIle : Javaconfig.java
package com.springcore.javaconfig;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages="com.springcore.javaconfig")

public class JavaConfig {
    

}

@Bean Annotation:
File : demo.java
package com.springcore.javaconfig;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Demo {
    public static void main(String[] args) {
       
        ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        
        Student std = (Student)context.getBean("getStudent", Student.class);
        System.out.println(std);
        std.study();    
    }
}

File : Javaconfig.java
package com.springcore.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfig {
      @Bean
      public Student getStudent() {
         return new Student();
      }
}
File : Student.java
package com.springcore.javaconfig;

public class Student {
    public void study() {
        System.out.println("Runnintg");
    }
}

Comments

Popular posts from this blog

Prectice page

ECMAScript Basics

Angular 2.0 complete course With Hands-on